这是我在论坛上的第一个问题,它与Zed的LPTHW ex38有关。我想要感谢您的任何和所有的帮助,我的查询beforehand.The代码的例子,我有一个问题就在这里。
ten_things = "Apples Oranges Crows Telephone Light Sugar"
stuff = ten_things.split(" ")
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print("Adding: ", next_one)
stuff.append(next_one)
print(f"There are {len(stuff)} items now.")关于这个脚本,我的第一个问题是在while循环中使用len(Stuff)。此变量包含一个字符串,该字符串是通过空格拆分的,在循环开始时,即使被拆分,它的值也应该是42。因为元素是通过pop从more_stuff中移除的,并且附加到了pop的末尾,所以这如何将len( stuff )值从一个字符更改为list中的元素(42个字符到10个元素)?
len(材料) 42
在拆分()之前和之后,len的值将为42。在append()之后,该值可能会更改为一个列表。我说错了吗?
我的第二个问题是,在本例中,您将如何替换for循环来代替while?
再次感谢!
发布于 2019-03-12 02:04:22
第一个问题:
您的代码有一个split,这就是为什么如果您没有这样做的话,它只有10个:
ten_things = "Apples Oranges Crows Telephone Light Sugar"
stuff = ten_things
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print("Adding: ", next_one)
stuff.append(next_one)
print(f"There are {len(stuff)} items now.")你会得到一个错误:
Adding: Boy
Traceback (most recent call last):
File "C:\Users\rep\Desktop\code\so.py", line 8800, in <module>
stuff.append(next_one)
AttributeError: 'str' object has no attribute 'append'这就是为什么。
第二个问题:
您可以这样使用for循环:
ten_things = "Apples Oranges Crows Telephone Light Sugar"
stuff = ten_things.split()
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
for i in more_stuff[::-1]:
if len(stuff) == 10:
break
else:
print("Adding: ", i)
stuff.append(i)
print(f"There are {len(stuff)} items now.")迭代more_stuff的反面,如果有10个元素,则执行if语句,否则相同。
发布于 2019-03-12 02:08:20
你把字符和元素弄混了。
mylist = ["element 1", "element2", "element_3"]
print(len(mylist)) #This will give you 3 on screen
#Because you are counting the elements
#not the words or the characters
#an element ends when a comma arrives.至于另一个问题,
...how,你会用一个for循环来代替这个例子中的while吗?
我做的代码与U9-Forward相同
发布于 2019-03-12 02:08:50
首先,stuff是一个数组,它不应该有值42。
拆分方法对字符串进行操作,并返回由分隔符分割的数组。
split文档:https://docs.python.org/3/library/stdtypes.html#str.split
所以这些东西的价值是:
['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar']条件len(stuff) != 10以6 != 10开头,因此代码继续追加来自more_stuff的元素,直到stuff数组的大小为10。
您的困惑是在split方法上。
对于第二个问题,您可以如下所示替代for循环:
for word in more_stuff:
if len(stuff) == 10:
break
stuff.append(word)https://stackoverflow.com/questions/55112975
复制相似问题