为了账号安全,请及时绑定邮箱和手机立即绑定

如何追加两个单独列表中的名称以追加和合并到一个列表

如何追加两个单独列表中的名称以追加和合并到一个列表

Smart猫小萌 2022-08-16 18:23:52
我正在尝试将名称追加到具有空字符串和空列表的空列表中。我想使用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'
查看完整描述

2 回答

?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

您的第一个元素是friendnum中的空字符串,因此您不能对字符串使用追加操作。此外,不能将元组中的值赋值为其不可变。


    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'])]


查看完整回答
反对 回复 2022-08-16
?
绝地无双

TA贡献1946条经验 获得超4个赞

问题数量:

  • i[0].append(tempName):是一个,因此不会有 。此外,你不能直接修改它,因为它已经在元组中并且它是不可变的。i[0]strappend

  • i[1].append(temp):由于是一个列表,将使其成为嵌套列表。你需要tempi[1].append(temp)extend

  • 由于两者都在就地操作,实际上什么也没做。appendextendnewList

相反,尝试使用列表理解的单行:

[(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'])]


查看完整回答
反对 回复 2022-08-16
  • 2 回答
  • 0 关注
  • 110 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号