我正在尝试将名称附加到具有空字符串和空列表的空列表中。 我想使用 for 循环或循环进行迭代,该循环将能够遍历friendsNum列表,并在字符串括号中插入来自peoplenames列表的随机名称,即i[0],然后在名为friendnames的列表中的两个随机名称之后空列表,即字符串后面的 i[1],并继续直到最后一个列表。
import random
friendsNum = [("",[]),("",[]),("",[]),("",[])]
peopleNames = ["Alvin","Danny","Maria","Lauren"]
friendNames = ("john","matt","will","mario","wilma","shannon","mary","jordan")
newList = friendsNum
tempName = ()
temp = ()
for i in friendsNum:
tempName = random.sample(peopleNames,1)
temp = random.sample(friendNames,2)
newList = i[0].append(tempName)
newList = i[1].append(temp)
在这个 for 循环迭代之后,它看起来像这样。
friendsNum = [("Johnny",["john","matt"]),
("Zach",["wilma","shannon"]),
("Dawn",["mary","jordan"]),
("Max",["will","john"])]
我不断收到无法从行中附加字符串对象的错误
newList = i[0].append(tempName)
newList = i[1].append(temp)
对于我应该使用的循环,我是否接近这个错误?
下面的错误消息
newList = i[0].append(tempName)
AttributeError: 'str' object has no attribute 'append'
最佳答案
问题数量:
i[0].append(tempName)
:i[0]
是一个str
,因此不会有追加
。此外,您不能直接修改它,因为它已经在元组中并且是不可变的。i[1].append(temp)
:由于temp
是一个列表,i[1].append(temp)
将使其成为一个嵌套列表。您需要延长
- 由于
append
和extend
都是就地操作,因此newList
实际上什么也不做。
相反,尝试使用列表理解的单行:
[(random.choice(peopleNames), random.sample(friendNames,2)) for i in range(len(peopleNames))]
输出:
[('Danny', ['shannon', 'john']),
('Maria', ['mary', 'shannon']),
('Lauren', ['matt', 'wilma']),
('Alvin', ['will', 'mario'])]
关于python - 如何将两个单独列表中的名称追加并合并到一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60482517/