python - 如何将两个单独列表中的名称追加并合并到一个列表

标签 python string list for-loop

我正在尝试将名称附加到具有空字符串和空列表的空列表中。 我想使用 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) 将使其成为一个嵌套列表。您需要延长
  • 由于 appendextend 都是就地操作,因此 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/

相关文章:

python - Jupyter Notebook 和 matplotlib(运行时警告): continue to display plots after closing

python - 我怎样才能杀死 python matplotlib 脚本?

c++ - 控制台输出中的意外字符

r - SQL 查询列表内的数据框

python - 在有条件的循环中列出索引超出范围

python - 在 Python 中将文本打印到行和列坐标?

python - "' NoneType ' object is not iterable"追加列表时出错

c++ - 在 C++ 中计算字符串中的字符出现次数

javascript - 使用复选框添加到 JavaScript 中的字符串

Python检查列表项是否为整数?