在 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
我看不到它有效,因为我会为两个列表错误地递增。
如有任何帮助,我们将不胜感激
一种简单的编码方法是使用 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)
试试这个,
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)]
输出
['a12', 'b34', 'c56', 'd78', 'e910', 'f1112']
我正在尝试加入两个具有不同数据长度的列表。
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
我看不到它有效,因为我会为两个列表错误地递增。
如有任何帮助,我们将不胜感激
一种简单的编码方法是使用 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)
试试这个,
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)]
输出
['a12', 'b34', 'c56', 'd78', 'e910', 'f1112']