簡體   English   中英

在 python 中以不等間隔加入不同長度的列表?

[英]Join lists of different lengths at unequal intervals in python?

我正在嘗試加入兩個具有不同數據長度的列表。

list1 = [a,b,c,d,e,f]
list2 = [1,2,3,4,5,6,7,8,9,10,11,12]

我想要的輸出是這樣的:

[a12, b34, c56, d78, e910, f1112

我的第一個想法是在不同的時間間隔做一些像增量 i

for i in printlist:
    for i in stats:
        print(printlist[i] + stats[i] + stats[i+1])

但這會吐出TypeError: list indices must be integers or slices, not str而且我看不到它的工作原理,因為我會為兩個列表錯誤地遞增。

任何幫助,將不勝感激

嘗試這個,

list1 = ["a","b","c","d","e","f"]
list2 = [1,2,3,4,5,6,7,8,9,10,11,12]

list3 = [str(i)+str(j) for i,j in zip(list2[::2], list2[1::2])]
["".join(list(x)) for x in zip(list1, list3)]

output

['a12', 'b34', 'c56', 'd78', 'e910', 'f1112']

一種簡單的編碼方法是使用 2 個計數器來跟蹤索引。 一個在每次迭代中增加 1,另一個在每次迭代中增加 2。 這將按如下方式完成:

list1 = ['a','b','c','d','e','f']
list2 = [1,2,3,4,5,6,7,8,9,10,11,12]

list3 = []
i = 0
j = 0
while i < len(list1):
  list3.append(list1[i] + str(list2[j]) + str(list2[j+1]))
  i += 1
  j += 2

print(list3)

但是你會注意到這里的j總是i值的兩倍(即j=2*i ),所以沒有必要有 2 個計數器。 所以你可以這樣簡化:

list1 = ['a','b','c','d','e','f']
list2 = [1,2,3,4,5,6,7,8,9,10,11,12]

list3 = []
for i in range(0, len(list1)):
  list3.append(list1[i] + str(list2[2*i]) + str(list2[2*i + 1]))

print(list3)

或作為列表理解:

list1 = ['a','b','c','d','e','f']
list2 = [1,2,3,4,5,6,7,8,9,10,11,12]

list3 = [list1[i] + str(list2[2*i]) + str(list2[2*i + 1]) for i in range(0, len(list1))]
print(list3)

暫無
暫無

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

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