如何将两个独立列表的名称合并为一个列表?

3
我正在尝试将名字附加到一个空列表中,该列表包含一个空字符串和一个空列表。我想使用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'

@Imm,请提供您所看到的错误信息。 - Todd
@Todd 刚刚放在底部,我希望我的问题对于我所尝试的事情是清晰的。我不确定我所尝试的事情是否可能。 - l.m.m
只需从 friendsNum 列表中删除字符串引号,然后进行附加操作即可。因为除非使用 join(),否则无法将任何内容附加到空字符串。 - de_classified
“i[0].append(tempName)”这一行代码是访问元组 ("", []) 的第一个成员,即字符串。您无法更改该字符串 - 元组是不可变的。您不能将另一个对象重新分配到元组中的位置。这是第一个问题。第二个问题是字符串也是不可变的,不支持像列表一样的 append() 方法。@Imm - 也许您想在元组的位置使用列表(它们可以被更新),并用tempName替换空字符串。 - Todd
2个回答

2

问题数量:

  • i[0].append(tempName)i[0] 是一个 str 类型,因此没有 append 方法。此外,由于它已经在元组中并且是不可变的,因此无法直接修改。
  • i[1].append(temp):由于 temp 是一个列表,i[1].append(temp) 将使其成为嵌套列表。你需要使用 extend 方法。
  • 由于 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'])]

1

你的friendsnum列表中第一个元素是空字符串,因此无法对字符串执行追加操作。另外,元组是不可变的,不能对其进行赋值操作。

    import random 
    friendsNum = [("",[]),("",[]),("",[]),("",[])]
    peopleNames = ["Alvin","Danny","Maria","Lauren"]
    friendNames = ("john","matt","will","mario","wilma","shannon","mary","jordan") 

    newList = []
    tempName = ()
    temp = ()
    for i in friendsNum:
        tempName = random.sample(peopleNames,1)
        temp = random.sample(friendNames,2)
        i = list(i)
        i[0] = (tempName[0])
        i[1] = (temp)
        newList.append(tuple(i))

使用上述更新的代码,以下是示例输出。
[('Danny', ['shannon', 'will']),
 ('Alvin', ['jordan', 'john']),
 ('Maria', ['mary', 'will']),
 ('Alvin', ['wilma', 'mary'])]

也许你可以提及如何处理朋友数元组中的内容,针对海报@Mohitsharma。 - Todd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接