簡體   English   中英

如何從兩個單獨的列表中附加名稱以附加並合並到一個列表

[英]How to append names from two separate lists to append and merge to one list

我正在嘗試將名稱附加到具有空字符串和空列表的空列表中。 我想使用 for 循環或能夠遍歷friendsNum 列表的循環進行迭代,並且在字符串括號中將從 peoplenames 列表中插入一個隨機名稱,即 i[0] 然后在列表中的兩個隨機名稱之后插入一個名為friendnames in空列表將是字符串后的 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 ,因此不會有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'])]

您的第一個元素是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'])]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM