我有2个列表:(list1,list2)我需要将这些列表合并到另一个列表中,该列表按此顺序包含list1
和list2
:
我试过了:
listNew = list1 + list2
for i in listNew:
listNew.append(i)
hranyNew.append(pocetHran/2+i)
但是有一个错误说:
+:' int'不支持的操作数类型和' str'
另一个问题是,如何将listNew[i]
和listNew[i+1]
与listNew[i+2]
和listNew[i+3]
进行比较?
换句话说,我需要将所有相邻对与pair+1
,2
等进行比较。
谢谢!
答案 0 :(得分:5)
我想指出非常方便的itertools.chain()
:
SITE DATE INDIV CATEGORY BIOMASS LENGTH
GC Oct A aqu 0.0002 10
GC Oct A n/a 0 0
GC Oct A terr 0 0
GC Oct B aqu 0 0
GC Oct B n/a 0 0
GC Oct B terr 0 0
GC Oct C aqu 0.1875 20
GC Oct C n/a 0 0
GC Oct C terr 0.5424 30
GC Aug D aqu 7.4888 10
GC Aug D n/a 0 0
GC Aug D terr 100.9245 5
GC Aug E aqu 0.0001 1
GC Aug E n/a 0 0
GC Aug E terr 0 0
GC Aug F aqu 0 0
GC Aug F n/a 0 0
GC Aug F terr 20.593 10
NSVhi Oct A aqu 5.8713 5
NSVhi Oct A n/a 0 0
NSVhi Oct A terr 13.8651 3
NSVhi Oct B aqu 17.2288 2
NSVhi Oct B n/a 0 0
NSVhi Oct B terr 0 0
NSVhi Oct C aqu 22.7558 1
NSVhi Oct C n/a 0 0
NSVhi Oct C terr 24.7843 6
NSVhi Aug D aqu 0 0
NSVhi Aug D n/a 0 0
NSVhi Aug D terr 31.9222 7
NSVhi Aug E aqu 0.046 10
NSVhi Aug E n/a 0 0
NSVhi Aug E terr 0 0
NSVhi Aug F aqu 2.1156 5
NSVhi Aug F n/a 0 0
NSVhi Aug F terr 0 0
您还可以使用带有双循环的list comprehension:
SITE DATE INDIV CATEGORY BIOMASS LENGTH
GC Oct C aqu 0.1875 20
GC Oct C n/a 0 0
GC Oct C terr 0.5424 30
GC Oct C aqu 0.1875 20
GC Oct C n/a 0 0
GC Oct C terr 0.5424 30
GC Oct A aqu 0.0002 10
GC Oct A n/a 0 0
GC Oct A terr 0 0
GC Aug D aqu 7.4888 10
GC Aug D n/a 0 0
GC Aug D terr 100.9245 5
GC Aug F aqu 0 0
GC Aug F n/a 0 0
GC Aug F terr 20.593 10
GC Aug D aqu 7.4888 10
GC Aug D n/a 0 0
GC Aug D terr 100.9245 5
NSVhi Oct B aqu 17.2288 2
NSVhi Oct B n/a 0 0
NSVhi Oct B terr 0 0
NSVhi Oct C aqu 22.7558 1
NSVhi Oct C n/a 0 0
NSVhi Oct C terr 24.7843 6
NSVhi Oct A aqu 5.8713 5
NSVhi Oct A n/a 0 0
NSVhi Oct A terr 13.8651 3
NSVhi Aug D aqu 0 0
NSVhi Aug D n/a 0 0
NSVhi Aug D terr 31.9222 7
NSVhi Aug D aqu 0 0
NSVhi Aug D n/a 0 0
NSVhi Aug D terr 31.9222 7
NSVhi Aug D aqu 0 0
NSVhi Aug D n/a 0 0
NSVhi Aug D terr 31.9222 7
如果您想在from itertools import chain
list1 = ['1','2','3']
list2 = ['a','b','c']
listNew = list(chain.from_iterable(zip(list1, list2)))
# listNew = ['1', 'a', '2', 'b', '3', 'c']
中连接元素对,那就是:
listNew = [y for x in zip(list1, list2) for y in x]
# listNew = ['1', 'a', '2', 'b', '3', 'c']
答案 1 :(得分:0)
merged_list = []
length = min([len(list1), len(list2)])
for l in range(0,length):
merged_list.append(list1[l])
merged_list.append(list2[l])
print merged_list