博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 内置函数_Python简介,第6章–内置函数和方法
阅读量:2519 次
发布时间:2019-05-11

本文共 31400 字,大约阅读时间需要 104 分钟。

python 内置函数



Magic-wielding escapees were desperately deflecting the Imperial attacks on the fortress’ supports as best they could. Ranks of longbowmen rained down arrows, but conjured gusts of wind sent many of them flying back the other way. The rebels were holding the Imperials off for the moment, but Baldric could see it was only a matter of time before they all took a dive, like so many employees before them, into the lake of fire.

中号 AGIC挥舞逃亡者拼命偏转,因为他们可以在最好的堡垒支持帝国的攻击。 弓箭手的队伍如雨点般落下,但是阵阵阵阵狂风使许多人以相反的方式飞回。 叛军暂时阻止了帝国军的进驻,但鲍德瑞克(Baldric)看到,像所有人一样,他们都跳入了火湖,这只是时间问题。

Of course, HR prisoners usually died by some other means first, such as repeated staff meetings. Ten a day, Baldric had heard. Then they were bundled up and stacked like firewood as he’d seen below before being tossed in the lava. Bundled up…the shrouds…

当然,人力资源囚犯通常会首先通过其他方式死亡,例如反复召开员工会议。 鲍德里克每天听到十声。 然后将它们捆起来,像柴火一样堆起来,就像他在下面看到的那样,然后扔进熔岩中。 捆绑了……裹尸布……

“Cassandra, the death shrouds HR uses. We’ve got some powerful Wind users here. What if we all grab a shroud and let the Wind guys float us out of here!?”

“卡桑德拉,死亡笼罩着人力资源部门。 我们这里有一些强大的Wind用户。 如果我们都抓起裹尸布,让风团伙把我们从这里赶出来,该怎么办!?”

One of the Wind users, a graying gnome, looked up at them. He seemed to think for a moment, then shrugged and said, “It won’t be easy, but we might be able to manage it.”

一个Wind用户,一个灰色的侏儒,抬头看着他们。 他似乎想了一会儿,然后耸了耸肩,说道:“这并不容易,但我们也许可以管理。”

After a moment of thought, Cassandra nodded. “The Great Serpent help us if that’s the best we’ve got. Sigh, get to it immediately.”

片刻之后,卡桑德拉点了点头。 “如果那是我们所能做到的最好的话,大蛇会帮助我们。 叹息,马上去。”

Baldric flew down the stairs and back to the storerooms of Block A. Weaving arms of Wind that gathered up all the shrouds into one big bundle, he carried them up to the roof, sweating with the concentration it took to maintain the flows of Wind. He emerged from the trapdoor back among the prisoners and pulled a huge bundle of shrouds up after him.

鲍德瑞克飞下楼梯,回到A块的储藏室。编织的风把所有的罩子捆成一捆,编织成一捆,然后抬起屋顶,集中精力维持风的流动。 他从囚犯的活板门中走出来,并在他身后拉出一大捆裹尸布。

Cassandra had apparently briefed everyone on the plan because on cue several individuals at a time ran over to the shrouds and quickly began unfolding and reconfiguring them and the accompanying ropes so that they became a sort of makeshift parasail wing with a rope through the middle of each of the two shorter sides that was then tied around one’s torso. But the rebel Magic users were visibly tiring from the efforts of the defense, and the additional lapse from rebels seeing to their escape shrouds gave the Imperials an opening. With a sickening crunch Baldric felt a main support give way.

卡桑德拉显然已经向所有人简要介绍了该计划,因为一次提示几个人跑到了围带上,并Swift展开并重新配置了围带和随附的绳索,以使它们成为一种临时的帆板机翼,每条绳索的中间都穿过绳索然后将两个短边中的一个绑在一个人的躯干上。 但是,叛军魔术师的用户显然在防御的努力上很累,而叛军看到逃生围裙的额外失误为帝国开辟了一块空地。 随着令人作呕的紧缩,波德里奇感到了主要的支持。

“Everyone ready?” Cassandra shouted.

“每个人都准备好了吗?” 卡桑德拉大喊。

One of the prisoners shouted back, “Wait, we’re short a shroud!” A 4-foot diameter fireball from the Imperials streaked through the air, leaving no trace of the prisoner it passed through behind.

其中一名囚犯大喊:“等等,我们简直是寿衣!” 帝国军发射的直径为4英尺的火球在空中划过,没有留下任何痕迹。

“Alright we’re good to go,” Cassandra responded. “Wind channelers, get us off this Light-forsaken thing!”

“好吧,我们很好。”卡桑德拉回答。 “风道者,让我们摆脱被光明抛弃的事情!”

Just as the fortress gave way under everyone’s feet, Baldric felt a strong updraft that instantly filled his death shroud parachute and carried him skyward. Like dandelion seeds, the ragtag rebels were blown through the air to the east towards the Teleportation Circle. The Imperials, caught by surprise, tried to pick them off with arrows and Magical projectiles, but the rebels were soon outside their range and on their way back to the city proper.

就像要塞在所有人的脚下屈服一样,鲍德瑞克感到强烈的上升气流,立即将他的死亡裹尸布降落伞降落,并抬高了他。 就像蒲公英的种子一样,破布的叛乱分子从空中被吹向东方,朝着隐形传送带。 帝国军措手不及,试图用箭和魔法弹头将他们赶下,但叛军很快就超出了他们的射程,并返回城市。

Cassandra floated over to Baldric. “We’ll be at the Teleportation Circle in several minutes, and you’ll need to unlock it ASAP. You’ll find three stone sphinxes, and each will have a puzzle to solve. Once those are are taken care of, that key I gave you will activate the Circle. I must warn you though, the puzzles involve heavy use of built-in functions, string methods, and list methods. But I have no doubt you can do it.”

卡桑德拉漂流到博尔德里克。 “我们将在几分钟之内到达Teleportation Circle,您需要尽快将其解锁。 您会发现三个石狮身人面像,每个都需要解决一个难题。 一旦解决了这些问题,我给您的那把钥匙就会激活圈子。 不过,我必须警告您,这些难题涉及大量使用内置函数,字符串方法和列表方法。 但我毫不怀疑您可以做到。”

“Well, that makes one of us,” Baldric muttered to himself. He began to ponder his chances of unlocking the Circle. Was he at that level yet? He knew at the very least he had a whole lot more to learn about built-in functions and methods, and he decided to see what he could figure out on his own.

“好吧,这使我们成为其中之一。”鲍德里克自言自语。 他开始考虑解锁圈子的机会。 他在那个水平了吗? 他至少知道,他还有很多要学习的有关内置函数和方法的知识,因此他决定看看自己能解决什么。

狮身人面像1 (Sphinx 1)

“I know that a built-in function is a function just like all the ones I’ve written, except I don’t actually have to write it. It’s just always there in the background, waiting for me to use it. And actually, now that I think about it, I’ve already used a lot of built-in functions without even realizing it.”

“我知道内置函数就像我编写的所有函数一样,只是我实际上不必编写它。 它一直都在后台,等着我使用它。 实际上,考虑到这一点,我已经使用了很多内置函数,甚至没有意识到它。”



print() Displays, or “prints out”, what’s passed into it. Useful in script mode where values aren’t printed to the console unless this function is called.

print ()显示或“打印出”传入的内容。 在脚本模式下很有用,在该模式下,除非调用此函数,否则不会将值打印到控制台。

# in interactive mode, print() often acts the same as just entering an expression without print()>>> 2 + 24>>> print(2 + 2)4
# in script mode, the result of 2+2 is not displayed2 + 2
 
# but with print(), now the script does print out the resulting valueprint(2 + 2)
4


type() Identifies the type of a given object.

type ()标识给定对象的类型。

>>> type(4)
>>> type("aren't there ever any bathroom breaks in adventures?")


int() Converts the passed object to an integer.

int ()将传递的对象转换为整数。

>>> int(4.2)4>>> int(4.9)4>>> int("4")4


float() Converts the passed object to a float.

float ()将传递的对象转换为float。

>>> float(4)4.0>>> float("4")4.0


str() Converts the passed object to a string.

str ()将传递的对象转换为字符串。

>>> str(4)'4'


list() Converts the passed object to a list.

list ()将传递的对象转换为列表。

>>> list('rebellion')['r', 'e', 'b', 'e', 'l', 'l', 'i', 'o', 'n']


range() Returns an iterable sequence of integers. Often used with for loops.

range ()返回整数的可迭代序列。 常与for循环一起使用。

>>> for i in range(1,5):        print(i)1234>>> for i in range(3):        print(i)012


len() Returns the length of a given object.

len ()返回给定对象的长度。

>>> len("sphinx")6>>> len(["sphinx 1", "sphinx 2", "sphinx 3"])3


“That’s quite a lot right there. But I wonder if there are other, perhaps even more powerful, built-in functions,” Baldric thought to himself.

“那有很多。 但我想知道是否还有其他甚至可能更强大的内置功能,” Baldric自言自语。

“Ah, excuse me Cassandra, I’ve got to go ask Boomdoom about something.” Baldric spotted the massive half-orc and floated over to him.

“啊,对不起,卡桑德拉,我得去问Boomdoom些事。” 鲍德里克发现了庞大的半兽人,然后向他漂浮。

“Uhh, hey Boomdoom.”

“呃,嘿,Boomdoom。”

“Doomboom.”

“ Doomboom。”

“Uh yeah, that’s what I meant (great start). Hey, about those built-in functions you were telling me about earlier, are there any more I should know about?” Baldric showed him the ones he’d just reviewed.

“是的,这就是我的意思(伟大的起点)。 嘿,关于您之前告诉我的那些内置函数,还有什么我应该知道的吗?” Baldric向他展示了他刚刚查看过的内容。

“Yes, there is one you must learn immediately and never forget: help(). If you are ever not sure what something is or what it will do, call help(). Say you are not sure what len() does.”

“是的,您必须立即学习并且永远不要忘记的一种: 帮助 ()。 如果您不确定什么是什么或将要做什么,请致电help ()。 说您不确定len ()会做什么。”



help() Gives you some hopefully helpful information on whatever object you pass it.

help ()给您一些有关传递的对象的有用信息。

# pass in the function len() to help# we want to input the actual function into help, and not call len()# and so we leave off the parentheses, just passing in the function's name>>> help(len)Help on built-in function len in module builtins:len(obj, /)    Return the number of items in a container.


“Simple, no? Now you know len() returns the number of items in a container, or in other words it tells you the length of something. Sometimes help() returns much information that can be difficult to understand. But with functions it will often give at least a helpful summary of what the function does and what arguments it takes. As another example, say you want to know more about print().”

“简单,不是吗? 现在,您知道len ()返回了容器中的项目数,换句话说,它告诉您事物的长度。 有时help ()返回许多可能难以理解的信息。 但是对于函数而言,它通常至少会至少对函数的功能以及所采用的参数给出有用的总结。 再举一个例子,假设您想进一步了解print ()。”

>>> help(print)Help on built-in function print in module builtins:print(...)    print(value, ..., sep=' ', end='n', file=sys.stdout, flush=False)        Prints the values to a stream, or to sys.stdout by default.    Optional keyword arguments:    file:  a file-like object (stream); defaults to the current sys.stdout.    sep:   string inserted between values, default a space.    end:   string appended after the last value, default a newline.    flush: whether to forcibly flush the stream.

“We already understand the basic use of print(). But now we see print() has a sep parameter, which is a single space by default. And this parameter determines what separates multiple printed values. What happens if we change sep to a smiley face?”

“我们已经了解了print ()的基本用法。 但是现在我们看到print ()有一个sep参数,默认情况下它是一个空格。 并且此参数确定分隔多个打印值的内容。 如果我们将sep变成笑脸会怎样?”

>>> print("rip", "emperor", "in", "half")rip emperor in half>>> print("rip", "emperor", "in", "half", sep=' :) ')rip :) emperor :) in :) half

“Wow, you sure know a lot Zoomzoom.”

“哇,您肯定对Zoomzoom知道很多。”

“Doomboom. Grandmother was wise, taught me much. But there are still other built-in functions you must know. I will show you now.”

“ Doomboom。 祖母很聪明,教会了我很多东西。 但是,您还必须知道其他内置函数。 我现在告诉你。”

Doomboom began to weave patterns of Logic entirely new to Baldric.

Doomboom开始编织Baldric全新的逻辑模式。



sum() Returns the sum of a list (or some other iterable) of numbers.

sum ()返回数字列表(或其他一些可迭代的数字)的总和。

>>> sum([1, 2, 3, 4])10>>> sum(range(5))10


min(), max() Returns the minimum or maximum of a list (or some other iterable) of numbers.

min (), max ()返回数字列表(或其他一些可迭代的数字)的最小值或最大值。

>>> nums = [23, 4, 66, 7]>>> max(nums)66>>> min(nums)4


round() Round a number to a given precision.

round ()将数字四舍五入到给定的精度。

>>> round(3.2468, 2)3.25>>> round(3.6)4


sorted() Returns a list of sorted values.

sorted ()返回一个排序值列表。

number_list = [23, 4, 66, 7]letter_list = ['b', 'a', 'd', 'c']letter_string = 'cats'>>> sorted(number_list)[4, 7, 23, 66]>>> sorted(letter_list)['a', 'b', 'c', 'd']>>> sorted(letter_string)['a', 'c', 's', 't']


At this point they were now descending swiftly towards the large Teleportation Circle in the heart of the city. Looking back, he could see the Imperial forces snaking through the streets in the direction of the Circle, but otherwise the city was quiet. Baldric thought he could just catch glimpses of movement here and there, but couldn’t ever quite make out what it was.

在这一点上,他们现在正Swift下降到城市中心的大型瞬移传送圈。 往回看,他可以看到帝国军队在圆环的方向上蜿蜒穿过街道,但除此之外,这座城市还是安静的。 鲍德瑞克以为他只是可以瞥见到处的动静,却无法完全分辨出那是什么。

Cassandra spoke up. “Once we land, we’re going to need to defend the Circle long enough for Baldric to unlock it. Then I’ll teleport away, and with any luck I’ll return with our army in short order. If you don’t want any part in this, no one will force you. You may leave as soon as we…” Cassandra was interrupted by screams as a swarm of whistling arrows flew through the group, puncturing parasails and body parts alike.

卡桑德拉开口了。 “一旦我们着陆,我们将需要保卫圆环足够长的时间,以使鲍德瑞克能够解锁它。 然后,我将远距离转移,如果运气好的话,我将在短时间内与我们的部队一起返回。 如果您不想参与其中,没有人会强迫您。 您可能会尽快离开我们……”卡桑德拉(Cassandra)被尖叫打断,一大群吹哨的箭头飞过人群,刺穿了帆板和身体部位。

Baldric could make out shapes now in the shadows of the windows and doorways below them. As another volley headed towards them, Baldric felt the winds abruptly shift and blow the arrows away. But the rebels were getting dispersed now, drawn every which way by the air currents, and many were sinking faster than others from the holes in their parasails. Cassandra barked one last command, “Everyone rendezvous at the Circle!” before she started launching icy volleys of her own back at the Imperials.

Baldric现在可以在窗户下方的门窗阴影中找出形状。 当另一排凌空驶向他们时,鲍德瑞克感到风突然转变并把箭吹走了。 但是叛军现在正在分散,被气流所吸引,许多人正比其他人更快地从帆旁的Kong中下沉。 卡桑德拉咆哮了最后一个命令,“每个人都在圈子集合!” 在她开始向帝国军发射自己的冰凌凌空之前。

It was chaos now, arrows flying in all directions and elemental death being fired in return. Buildings went up in flame from roaring firebolts. Dust devils arose among the Imperials, obscuring their view of the sky. Lightning rained down on clumps of soldiers, sending them flying. Baldric just kept his sights on the Circle, steering himself towards it as stealthily as he could. He landed and, amid the swirling dust and cries of battle, made his way over to one of the stone sphinxes. At the base of the statue was an inscription of a list of numbers and some text.

现在是一片混乱,四面八方的箭飞来,而元素死亡则被发射。 轰鸣的炮楼使建筑物起火。 帝国之间散发着尘土飞扬,使他们看不到天空。 闪电降落在成群的士兵身上,使他们飞行。 鲍德里克(Baldric)只是将目光投向了圈子,尽自己所能地悄悄地朝着圈子走去。 他降落,在旋风飞扬的沙尘和战斗的叫喊声中,他来到了一只狮身人面像上。 雕像的底部刻有数字和一些文字的铭文。

751.553187794811, 798.553187794811, 4133.8085586674515, 786.553187794811, 792.553187794811, 807.553187794811, 783.553187794811, 810.553187794811, 795.553187794811, 813.553187794811, 819.553187794811, 804.553187794811, 789.553187794811, 816.553187794811"""minimum by maximum by sum by count, rounded"""

“Hmm, I’m gonna go ahead and guess I need to take the product of the minimum, maximum, sum, and length of the list. Well let’s see…if I wanted a function that can find the largest number in a list of numbers, I bet I could do something like this:”

“嗯,我要继续,我想我需要取列表的最小,最大,总和和长度的乘积。 好吧,让我们看看……如果我想要一个可以在数字列表中找到最大数字的函数,我敢打赌我可以做这样的事情:”

def maximum(nums):    max_so_far = 0    for num in nums:        if num > max_so_far:            max_so_far = num    return max_so_far

“But wait a second, something’s tickling the back of my mind…of course, I can just use the built-in max() function! In fact, all these procedures the sphinx wants have a corresponding built-in function.”

“但是,请稍等片刻,这让我很后悔……当然,我可以使用内置的max ()函数! 实际上,狮身人面像想要的所有这些程序都具有相应的内置功能。”

>>> numbers = [    751.553187794811,     798.553187794811,     4133.8085586674515,     786.553187794811,     792.553187794811,     807.553187794811,     783.553187794811,     810.553187794811,     795.553187794811,     813.553187794811,     819.553187794811,     804.553187794811,     789.553187794811,     816.553187794811    ]>>> max(numbers)4133.8085586674515>>> min(numbers)751.553187794811>>> sum(numbers)14503.99999999999>>> len(numbers)14

“Everything looks like it’s working, so let’s see if taking the product works.”

“一切看起来都很正常,所以让我们看看使用该产品是否可行。”

>>> answer = max(numbers) * min(numbers) * sum(numbers) * len(numbers)>>> print(answer)630849710511.9988

“Hmm, nothing happened. Guess I’ll round it to the nearest whole number.”

“嗯,什么都没发生。 猜猜我会四舍五入到最接近的整数。”

>>> print(round(answer))630849710512

The sphinx’s eyes glowed a bright green. Baldric looked around for the next sphinx. He noticed for the first time, through all the dust and smoke, that hundreds of rebels were all around him now, with Cassandra running around and barking orders. Four major streets all fed into the roundabout surrounding the sizable Circle, so four different groups were defending their respective streets. Wagons and carts and crates were all being magically whisked through the air to be placed in growing barricades that rebels just finding the Circle were scurrying over.

狮身人面像的眼睛闪耀着鲜绿色。 鲍德里克环顾四周,寻找下一个狮身人面像。 他通过尘土和烟雾第一次注意到,现在有数百名叛乱分子围在他周围,卡桑德拉(Cassandra)到处乱跑并咆哮。 四个主要街道都进入了环绕较大的Circle的回旋处,因此四个不同的团体在捍卫自己的街道。 货车,马车和板条箱都被空中神奇地搅打,被放置在不断增长的路障中,而叛乱分子只是发现“铁环”而已。

Cries broke out to the north, followed by a shower of arrows the rebels took cover from. Dust devils laced with ice shards were sent down the street in response. To the west, the rebels cursed as their barricade ignited in flame. But after blowing apart the second story of the building where the flames had shot from with a series of lightning bolts and dowsing the barricade’s flames with Water, the west road was quiet once again.

北方爆发了哭声,随后叛军掩饰了阵阵箭雨。 作为回应,被冰碎片缠着的尘暴被送到街上。 在西部,叛军在街垒点燃时大骂。 但是,在用一连串的闪电炸毁了建筑物的第二层建筑之后,西路又安静了起来。

狮身人面像2 (Sphinx 2)

Baldric hurried over to a second sphinx and inspected the inscription.

鲍德瑞克急忙走到第二个狮身人面像并检查了铭文。

'the boots','of destruction','of ten','the wizard','of boredom','of doom','of power','the staff meetings','of rot','of servitude','the pencil sharpeners','the crystal','of blinding speed','the mind games','the gossip','the god','of dreams','of light','the groups','of logic','the hammer','of darkness','the axe','the performance reviews'"""take only those of length 6 or 10,then pop index 5 and insert at the start,taking the first two as your answer"""

“Based on these instructions, I’m gonna guess I’ll probably want to use a few list methods. Let’s see…methods…yeah, not ringing a bell.”

根据这些说明,我可能会想使用一些列表方法。 让我们看看……方法……是的,不要敲钟。”

A familiar voice rumbled behind Baldric. “Looks like you need list methods. I will show you now.”

鲍德瑞克身后传来一个熟悉的声音。 “看起来您需要列表方法。 我现在告诉你。”

Baldric turned around to find Doomboom standing behind him. “First, remind me again, what are methods exactly?”

鲍德瑞克转过身去,发现道蓬姆站在他身后。 “首先,再次提醒我,确切的方法是什么?”

“Methods are functions, just like built-in functions or functions you write yourself. The difference is that methods are contained inside other objects, like lists or strings, and can only be accessed through these objects. The terminology can overlap since the string and list methods are also technically built-in functions, but don’t be too concerned about these distinctions. Here are some examples of using list methods.”

“方法就是函数,就像内置函数或您自己编写的函数一样。 不同之处在于方法包含在其他对象(例如列表或字符串)中,并且只能通过这些对象进行访问。 术语可能会重叠,因为字符串和列表方法也是技术上内置的函数,但不必太在意这些区别。 这是一些使用列表方法的例子。”



list.append() Appends an object to the end of the list.

清单。 append ()将对象追加到列表的末尾。

>>> letters = ['a', 'b', 'c']>>> letters.append('d')>>> print(letters)['a', 'b', 'c', 'd']


list.extend() Appends all objects in an iterable to the end of a list.

清单。 extend ()将可迭代的所有对象追加到列表的末尾。

>>> letters = ['a', 'b']>>> letters.extend(['c', 'd'])>>> print(letters)['a', 'b', 'c', 'd']


list.insert() Inserts an object at the given list index.

清单。 insert ()在给定的列表索引处插入一个对象。

>>> letters = ['a', 'b', 'c']>>> letters.insert(1, 'd')>>> print(letters)['a', 'd', 'b', 'c']


list.pop() Removes and returns object at index (default is last).

清单。 pop ()删除并返回索引处的对象(默认为最后)。

>>> letters = ['a', 'b', 'c', 'd']>>> letters.pop()'d'>>> print(letters)['a', 'b', 'c']>>> letters.pop(0)'a'>>> print(letters)['b', 'c']


list.remove() Removes first occurrence of object in list.

清单。 remove ()删除列表中第一次出现的对象。

>>> letters = ['a', 'b', 'c', 'b']>>> letters.remove('b')>>> print(letters)['a', 'c', 'b']


list.clear() Remove all items from the list.

清单。 clear ()从列表中删除所有项目。

>>> letters = ['a', 'b', 'c']>>> letters.clear()>>> print(letters)[]


list.index() Returns the index of the first occurrence in list of passed object.

清单。 index ()返回传递的对象列表中第一次出现的索引。

>>> letters = ['a', 'b', 'c', 'b']>>> letters.index('b')1


list.count() Returns the number of times the passed object occurs in the list.

清单。 count ()返回传递的对象在列表中出现的次数。

>>> letters = ['a', 'b', 'c', 'b']>>> letters.count('b')2


“Notice how some of these list methods modified their list, and did so without requiring any sort of variable assignment. In other words, the lists were modified “in place”. It’s a common error to do something like…”

“请注意,这些列表方法中的某些方法是如何修改其列表的,并且不需要任何类型的变量分配即可进行修改。 换句话说,列表被“就地”修改。 做类似的事情是常见的错误……”

>>> hobbies = ['smash', 'bash', 'flatten']>>> hobbies = hobbies.append(['crush'])>>> print(hobbies)None# append() doesn't return anything, or to be precise it returns None# because it modifies the list in place, no variable assignment required

“…when you should have instead done…”

“……当你应该做的时候……”

>>> hobbies = ['smash', 'bash', 'flatten']>>> hobbies.append(['crush']) # modify the list in place>>> print(hobbies)['smash', 'bash', 'flatten', 'crush']

“And if you ever forget what a method does, use help() like so.”

“而且,如果您忘记了方法的作用,请像这样使用help ()。”

# you have to reference count() via a list# so you can use any list, including an empty list as shown here>>> help([].count)Help on built-in function count:count(...) method of builtins.list instance    L.count(value) -> integer -- return number of occurrences of value

“If you want help on all list methods, just pass in any list to help(). For now, just ignore anything that starts with underscores. Look past those to see the methods I just showed you.”

“如果您需要所有列表方法的帮助,只需将任何列表传递给help ()。 现在,只需忽略任何以下划线开头的内容。 看看那些,看看我刚才给你看的方法。”

>>> help([])# pass in an empty list to help() yourself to see the lengthy output

“Sometimes though, you just want a quick list of method names to jog your memory. For this, use the dir() function.”

“有时候,您只是想要一个快速的方法名列表来慢跑您的记忆。 为此,请使用dir ()函数。”

>>> dir([])['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

“Again, ignore the names that start with underscores. That will come later in your training. And keep in mind you may also use dir() without any arguments just to see what the available names are currently, such as what the names are of the variables or functions you’ve already defined.”

再次,请忽略以下划线开头的名称。 那将在您的培训中稍后介绍。 并且请记住,您也可以使用不带任何参数的dir ()只是为了查看当前可用的名称,例如已经定义的变量或函数的名称。”

“Thanks Choomfloom…”

“感谢Coomfoom……”

“Doomboom.”

“ Doomboom。”

“…I think I get it now.”

“……我想我现在明白了。”

There was some commotion from the east road, and Doomboom left to see to it. Baldric turned his attention back to the sphinx’s inscription.

东路有一些骚动,唐博姆(Doomboom)离开去看看。 鲍德瑞克将注意力转向狮身人面像的铭文。

“First things first, I’ll filter out all the strings from the list that aren’t of length 6 or 10.”

“首先,我将从列表中过滤掉所有长度不为6或10的字符串。”

"""take only those of length 6 or 10,then pop index 5 and insert at the start,taking the first two as your answer"""phrases = ['the boots', 'of destruction', 'of ten', 'the wizard', 'of boredom', 'of doom', 'of power', 'the staff meetings', 'of rot', 'of servitude', 'the pencil sharpeners', 'the crystal', 'of blinding speed', 'the mind games', 'the gossip', 'the god', 'of dreams', 'of light', 'the groups', 'of logic', 'the hammer', 'of darkness', 'the axe', 'the performance reviews']filtered_phrases = []for e in phrases:  if (len(e) == 10) or (len(e) == 6):    filtered_phrases.append(e)print(filtered_phrases)
['of ten', 'the wizard', 'of boredom', 'of rot', 'the gossip', 'the groups', 'the hammer']

“Next I’ll use the list.pop() method on the fifth list element, then insert it at the starting position.”

“接下来,我将使用该列表。 将pop ()方法放在第五个列表元素上,然后将其插入起始位置。”

popped_element = filtered_phrases.pop(5)filtered_phrases.insert(0, popped_element)print(filtered_phrases)
['the groups', 'of ten', 'the wizard', 'of boredom', 'of rot', 'the gossip', 'the hammer']

“And finally I just need to grab the first two list elements and I should have my answer.”

“最后,我只需要获取前两个列表元素,就可以得到答案。”

answer = filtered_phrases[0] + ' ' + filtered_phrases[1]print(answer)
the groups of ten

The second sphinx’s eyes lit up green. Baldric began to run over to the next sphinx when the relative calm broke all at once. Several boulders crashed into the Circle, while all four streets filled with legions of mounted Imperial guardsmen and gliders overhead dropped dropped some sort of handheld explosives. Dodging several explosions and crossbow bolts, Baldric found himself in the path of charging mounted Imperials. Baldric wove Wind, and several quick concentrated bursts of air blew the soldiers off their mounts. Baldric fell to the ground dodging the horses, and saw following in their path a massive, rumbling boulder.

第二只狮身人面像的眼睛变成绿色。 当相对平静一下子打破时,鲍德瑞克开始跑到下一个狮身人面像。 几块巨石坠入了环形山,四条街道上都挤满了大批骑警卫兵和高空滑翔机,掉落了一些手持炸药。 鲍德里克躲过几场爆炸和cross弓箭,发现自己正在向装甲的帝国部队冲锋。 秃头编织了风,阵阵阵阵阵阵空袭使士兵们从坐骑上飞了下来。 鲍德里克(Baldric)躲在地上躲着马匹,在他们的行进中看到一条巨大的隆隆的巨石。

A guttural roar sounded behind him, followed by Doomboom sprinting past him to shoulder the boulder straight on, stopping its momentum dead. Baldric saw once again Doomboom’s Magic being woven straight into himself in a sort of circular fashion. The half orc’s hands dug into the boulder and somehow found a grip. He tugged it off the ground and with several spins released it, sending it crashing into a nearby building.

身后传来阵阵吼叫声,随后Doomboom从他身旁冲了过去,直站着巨石,阻止了它的冲劲。 Baldric再次看到Doomboom的Magic以一种圆形的方式直接编织到自己身上。 半个兽人的手伸入巨石中,以某种方式找到了抓地力。 他将它拖离地面,并旋转了几下,将其撞到附近的建筑物中。

The boulder uncurled among the ruin and revealed itself to be a scaly, four-legged monstrosity. It jumped to its feet and ran at Doomboom, hacking up a projectile stream of liquid as it advanced. Doomboom rolled out of the way, pulled a heavy iron lantern pole out of the ground like a weed and brought it down on the charging creature’s head with a sickening crunch. It lay still. Baldric noticed the ground where it’s spit landed had dissolved into a large pit.

巨石在废墟中卷曲,露出自己是鳞状,四足的怪兽。 它跳了起来,冲向Doomboom,在前进时劈开了射流的液体。 Doomboom滚开,像杂草一样从地上拉出一个沉重的铁灯笼杆,并用令人作呕的咬嚼把它放倒在充电生物的头上。 它静止不动。 鲍德里克(Baldric)注意到吐唾沫的地面已经溶解成一个大坑。

“Baldric,” Doomboom shouted over the din, “That last sphinx requires string methods. Unlock it with haste.” And with that he was off, diving right into the middle of a nearby skirmish.

“ Baldric,” Doomboom在din上喊道,“最后一个狮身人面像需要使用字符串方法。 急忙解锁。” 然后他离开了,潜入附近小冲突的中间。

狮身人面像3 (Sphinx 3)

Taking cover behind a small stone well, Baldric hastily studied string methods with the use of dir() and help().

在一个小石井的后面盖上了盖子,Baldric用dir ()和help ()匆忙研究了字符串方法。



str.upper() Returns an uppercase copy of the string.

海峡 upper ()返回字符串的大写副本。

>>> "Baldric Hightower".upper()'BALDRIC HIGHTOWER'


str.lower() Returns a lowercase copy of the string.

海峡 lower ()返回字符串的小写副本。

>>> 'Baldric Hightower'.lower()'baldric hightower'


str.title() Returns a copy of the string with the first letter of every word capitalized.

海峡 title ()返回字符串的副本,每个单词的首字母大写。

>>> 'only three demons and one dwarf so far'.title()'Only Three Demons And One Dwarf So Far'


str.index() Returns the index of the first match of the passed substring.

海峡 index ()返回所传递子字符串的第一个匹配项的索引。

>>> 'one sphinx to go'.index('sphinx')4


str.count() Returns the number of substring occurrences in the string.

海峡 count ()返回字符串中出现子字符串的次数。

>>> 'if I had a copper for every copper in this string...'.count('copper')2


str.isalnum() Returns True if string contains only letters and numbers, otherwise False.

海峡 isalnum ()如果字符串仅包含字母和数字,则返回True,否则返回False。

>>> 'five'True>>> '500'True>>> '$500'False>>> 'five hundred'False


str.replace() Replaces every instance of first substring with second substring.

海峡 replace ()用第二个子字符串替换第一个子字符串的每个实例。

>>> 'soon the assault begins'.replace('s', '$')'$oon the a$$ault begin$'


str.split() Returns a list of strings split apart on passed substring.

海峡 split ()返回在传递的子字符串上分开的字符串列表。

>>> 'may-the-light-protect-us'.split('-')['may', 'the', 'light', 'protect', 'us']


str.join() Uses the string to concatenate all elements of the passed iterable.

海峡 join ()使用字符串连接所传递的Iterable的所有元素。

>>> '-'.join(['may', 'the', 'light', 'protect', 'us'])'may-the-light-protect-us'


“Hmm, string methods seem pretty similar to list methods. Well, here goes nothing.”

“嗯,字符串方法似乎与列表方法非常相似。 好吧,这里什么也没有。”

Baldric ran to the final sphinx and hurriedly inspected the inscription.

鲍德里克跑到最后的狮身人面像,急忙检查了铭文。

"""!!$@$$Rze?j&&@mexz!?mb!e@?$$$r ja!l@$?$$zw&&aj?@!$$$y@zs:!&&B@!u$$?$s?yzn!@e?s$$$s z?@$?$$isx $$$P?@&&r!jog@z?rjes@!s!,$?$$O!bex@?z!di&@&?ezn?$?$@$c@e! izs F$@$$r?@eze?x$$$d@joxm,!&&P!@ro?$$$@zf!@it qis@$?$$ $$@$!P&&@urp??@zo@se,!$?$$&&A!@u?z$$@$tjh@$$$!@jo?ritz@&&y @ixs zD@$$$i@vz?i!@ne!@&?&,$@$$?axz@n!d &@&W!o!$$@$!@zr&&k ji@zs z&&@Li?!$@$?$@fxe.!!?""""""get counts for characters z!$&@qxj?j&zthen remove charactersand use counts as indices"""

“Basically it looks like there’s this one long string I need to clean up, and then use the count of certain characters prior to the cleaning process to pick out characters by their index after cleaning. And it looks like string methods are needed, just like Badabing Badaboom said.”

“基本上看来,我需要清理这一个长字符串,然后在清理过程之前使用某些字符的计数,以根据清理后的索引选择字符。 就像Badabing Badaboom所说的那样,似乎需要字符串方法。”

“So to get counts of characters, I think I can just use the string.count() method.”

“因此,要获得字符数,我想我只能使用字符串。 count ()方法。”

>>> s = """!!$@$$Rze?j&&@mexz!?mb!e@?$$$r ja!l@$?$$zw&&aj?@!$$$y@zs:!&&B@!u$$?$s?yzn!@e?s$$$s z?@$?$$isx $$$P?@&&r!jog@z?rjes@!s!,$?$$O!bex@?z!di&@&?ezn?$?$@$c@e! izs F$@$$r?@eze?x$$$d@joxm,!&&P!@ro?$$$@zf!@it qis@$?$$ $$@$!P&&@urp??@zo@se,!$?$$&&A!@u?z$$@$tjh@$$$!@jo?ritz@&&y @ixs zD@$$$i@vz?i!@ne!@&?&,$@$$?axz@n!d &@&W!o!$$@$!@zr&&k ji@zs z&&@Li?!$@$?$@fxe.!!?""">>> s.count('z')21

“21 z’s. That seems to work. Then if I want to get the counts for all the characters…”

“ 21Z。 这似乎有效。 然后,如果我想获得所有字符的计数……”

>>> s = """!!$@$$Rze?j&&@mexz!?mb!e@?$$$r ja!l@$?$$zw&&aj?@!$$$y@zs:!&&B@!u$$?$s?yzn!@e?s$$$s z?@$?$$isx $$$P?@&&r!jog@z?rjes@!s!,$?$$O!bex@?z!di&@&?ezn?$?$@$c@e! izs F$@$$r?@eze?x$$$d@joxm,!&&P!@ro?$$$@zf!@it qis@$?$$ $$@$!P&&@urp??@zo@se,!$?$$&&A!@u?z$$@$tjh@$$$!@jo?ritz@&&y @ixs zD@$$$i@vz?i!@ne!@&?&,$@$$?axz@n!d &@&W!o!$$@$!@zr&&k ji@zs z&&@Li?!$@$?$@fxe.!!?""">>> chars = "z!$&@qxj?j&z">>> counts = []>>> for char in chars:      counts.append(s.count(char))>>> print(counts)[21, 31, 66, 26, 46, 1, 8, 9, 32, 9, 26, 21]

“Perfect, so there’s 21 z’s, 31 exclamation marks, and so on. Now I need to remove all these characters from the string. I think there’s a string method that can do that too. Using string.replace(), I can replace all the unwanted characters with empty strings.”

完美,所以有21个z,31个感叹号,依此类推。 现在,我需要从字符串中删除所有这些字符。 我认为有一个字符串方法也可以做到这一点。 使用字符串。 replace (),我可以将所有不需要的字符替换为空字符串。”

>>> for char in chars:        s = s.replace(char, "")>>> print(s)Remember always:Busyness is Progress,Obedience is Freedom,Profit is Purpose,Authority is Divine,and Work is Life.

“Ah, what a lovely message. Anyways, now I have to use the character counts as indices to pick out a message from this string.”

“啊,真是个好消息。 无论如何,现在我必须使用字符数作为索引来从该字符串中选择一条消息。”

>>> answer = "">>> for i in indices:        answer += s[i]>>> print(answer)'notice again'

The third and final sphinx’s eyes glowed green. An eye-shaped hole opened up in the sphinx’s forehead. Baldric pulled out the Teleportation Circle key and slid it in. It clicked into place and lit up, resembling a third green glowing eye. Baldric wanted to cry out in celebration, but found himself drawn into the sphinx’s three-eyed gaze. Green filled his vision, and into the green he went. Green faded to black, and through an endless night he traveled.

第三只也是最后一只狮身人面像的眼睛发绿。 狮身人面像的额头上开了一个眼睛形的洞。 Baldric拔出Teleportation Circle钥匙并将其滑入。它咔嗒一声固定到位并亮起,类似于第三只绿色发光的眼睛。 鲍德里克想为庆祝而大喊大叫,但发现自己被狮身人面像的三眼目光所吸引。 格林充满了他的视野,他走进了绿色。 绿色渐渐消失为黑色,他经过了无尽的夜晚。



Congratulations, you earned 2,139 experience and 1,742 gold. You are now a Level 8 Dwarven Warlock!()

恭喜,您获得了2139点经验和1,742金。 您现在是8级矮人术士! ( )

Here are the Python topics you covered (and may want to for further inquiry):

这是您涵盖的Python主题(并且可能需要进行进一步的查询):

  • (including help() and dir())
  • (包括help ()和dir ())


翻译自:

python 内置函数

转载地址:http://xgqwd.baihongyu.com/

你可能感兴趣的文章
初识react
查看>>
jzoj5843
查看>>
学习swift开源项目
查看>>
[BZOJ 1293] 生日礼物
查看>>
Hadoop以及组件介绍
查看>>
1020 Tree Traversals (25)(25 point(s))
查看>>
第一次作业
查看>>
“==”运算符与equals()
查看>>
sqlite3
查看>>
软件工程:黄金G点小游戏1.0
查看>>
如何使用Powershell脚本监控Exchange2010(一) 数据库Mount状态的监控
查看>>
leetcode 144. Binary Tree Preorder Traversal
查看>>
理解 LINUX 的处理器负载均值(翻译)
查看>>
Struts2 流程原理
查看>>
Exp5 msf实践
查看>>
ElasticSearch简要总览
查看>>
浏览器的工作原理
查看>>
2.4.6 计算机语言表示算法
查看>>
Android SDK简介-读书笔记(一)
查看>>
android 构建数据库SQLite
查看>>