iT邦幫忙

0

Python 兩個 list 合併

如題,有兩個List
其中
A List 各列 想對應 B List 每一列
逐步形成水平合併的list形式

https://ithelp.ithome.com.tw/upload/images/20200119/20111873vC9Kp304fC.png

temp = []
tempU = []
userANDitem = []

for userLen in range(len(user_list)-1):
    tempU.clear()
    #每一個 user 5 欄位
    for x in range(5):
        tempU = temp.append(user_list[userLen+1][x])
    # 共 40 個  物品
    for questionLen in range(len(question_list)-1):
        #物品中共 6 個欄位
        for y in range(6):
            print(y)
            temp.append(question_list[questionLen+1][y])
            print(temp)
            if(y==5):
                userANDitem.append(temp)
                temp.clear()
                temp.append(tempU)
                print("------userANDitem--------")
                print(userANDitem)
                print("--------------")

但不知為何出來的list都只會重複,
已寫了兩天但還是無法想出,懇請各位大大幫忙,
謝謝

不考慮

  • numpy 是因為只能對數字操作,但資料格式含有String
  • pandas 是因為pandas只能針對各列一對一水平合併,且有index問題
黃彥儒 iT邦高手 1 級 ‧ 2020-01-19 23:18:23 檢舉
看不懂,你能給出範例輸入與你期望的輸出嗎?
p39212053 iT邦新手 4 級 ‧ 2020-01-20 14:17:46 檢舉
像是A list中有 [a,b,c]、[d,e,f]
B list中有 [1,2,3,4] 、[5,6,7,8]、[9,10,11,12]

出來的結果要是
[a,b,c,1,2,3,4]
[a,b,c,5,6,7,8]
[a,b,c,9,10,11,12]
[d,e,f,1,2,3,4]
[d,e,f,5,6,7,8]
[d,e,f,9,10,11,12]
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
2
PoiBlackTea
iT邦新手 4 級 ‧ 2020-01-20 14:13:01
最佳解答

感覺問題出在對python 賦值理解問題,因為不清楚輸入輸出,所以以下僅供參考。

import copy

temp = []
tempU = []
userANDitem = []

for userLen in range(len(user_list)-1):
    
    #每一個 user 5 欄位
    temp.extend(user_list[userLen+1])
    tempU = [copy.deepcopy(i) for i in temp]

    # 共 40 個  物品
    for questionLen in range(len(question_list)-1):
        #物品中共 6 個欄位
        temp.extend(question_list[questionLen+1])
        print(temp)
        userANDitem.append(copy.deepcopy(temp))
        temp.append(tempU)
        print("------userANDitem--------")
        print(userANDitem)
        print("--------------")
        temp.clear()
1
張小馬~
iT邦新手 3 級 ‧ 2020-01-20 14:42:10
list = []
for x in range(len(A)):
    for y in range(len(B)):
        print(A[x]+B[y])
        list.append(A[x]+B[y])

https://ithelp.ithome.com.tw/upload/images/20200120/20111566kokAaAz7Wc.png

p39212053 iT邦新手 4 級 ‧ 2020-01-20 15:32:57 檢舉

感謝您~

2
I code so I am
iT邦高手 1 級 ‧ 2020-01-20 16:09:54
list1=[ ['a','b','c'],['d','e','f']]
list2=[ [1,2,3,4],[5,6,7,8],[9,10,11,12]]

x=[i + j for i in list1  
        for j in list2]
x        

結果如下:
[['a', 'b', 'c', 1, 2, 3, 4],
['a', 'b', 'c', 5, 6, 7, 8],
['a', 'b', 'c', 9, 10, 11, 12],
['d', 'e', 'f', 1, 2, 3, 4],
['d', 'e', 'f', 5, 6, 7, 8],
['d', 'e', 'f', 9, 10, 11, 12]]

edison02 iT邦新手 4 級 ‧ 2020-02-05 17:19:57 檢舉

簡潔的寫法!/images/emoticon/emoticon34.gif

我要發表回答

立即登入回答