list1 = [['WA', 'WA'], ['DC'], ['HI'], ['NJ', 'NJ', 'NJ', 'NJ', 'NJ'], ['TX', 'TX', 'TX'], ['LA', 'LA'], ['NC'], ['NY'], ['IL', 'IL'], ['GA'], ['MA'], ['AZ']]
list2 = [0.875, 10.875, 0, 0, 0, 0, 0.0, 0.0, 10.0, 0, 0, 0, 0.625, -0.25, 0, 10.0, 0.5, 0, 0, 10.0, 9.25]
我希望list3是这样的:
list 3 = [[0.875, 10.875], [0], [0], [0, 0, 0.0, 0.0, 10.0], [0, 0, 0], [0.625, -0.25], [0], [10.0], [0.5, 0], [0], [10.0], [9.25]]
我已经得到了list1的索引:
index_list = [[0, 1], [2], [3], [4, 5, 6, 7, 8], [9, 10, 11], [12, 13], [14], [15], [16, 17], [18], [19], [20]]
答案 0 :(得分:1)
以下是使用itertools.accumulate()
的解决方案。
from itertools import accumulate
list1 = [['WA', 'WA'], ['DC'], ['HI'], ['NJ', 'NJ', 'NJ', 'NJ', 'NJ'], ['TX', 'TX', 'TX'], ['LA', 'LA'], ['NC'], ['NY'], ['IL', 'IL'], ['GA'], ['MA'], ['AZ']]
list2 = [0.875, 10.875, 0, 0, 0, 0, 0.0, 0.0, 10.0, 0, 0, 0, 0.625, -0.25, 0, 10.0, 0.5, 0, 0, 10.0, 9.25]
# temp to track the starting and ending index positions of the sublists
temp = [0] + list(accumulate(len(x) for x in list1))
# [0, 2, 3, 4, 9, 12, 14, 15, 16, 18, 19, 20, 21]
list3 = [list2[j:temp[i+1]] for i, j in enumerate(temp[:-1])] # See 1
# >> [[0.875, 10.875], [0], [0], [0, 0, 0.0, 0.0, 10.0], [0, 0, 0], [0.625, -0.25], [0], [10.0], [0.5, 0], [0], [10.0], [9.25]]
list3 = [list2[i:j] for i, j in zip(temp[:-1], temp[1:])]
。答案 1 :(得分:1)
直接地:
list1 = [['WA', 'WA'], ['DC'], ['HI'], ['NJ', 'NJ', 'NJ', 'NJ', 'NJ'], ['TX', 'TX', 'TX'], ['LA', 'LA'], ['NC'], ['NY'], ['IL', 'IL'], ['GA'], ['MA'], ['AZ']]
list2 = [0.875, 10.875, 0, 0, 0, 0, 0.0, 0.0, 10.0, 0, 0, 0, 0.625, -0.25, 0, 10.0, 0.5, 0, 0, 10.0, 9.25]
result = []
c = 0
for item in list1:
item_len = len(item)
result.append(list2[c: c+item_len])
c += item_len
print(result)
输出:
[[0.875, 10.875], [0], [0], [0, 0, 0.0, 0.0, 10.0], [0, 0, 0], [0.625, -0.25], [0], [10.0], [0.5, 0], [0], [10.0], [9.25]]
答案 2 :(得分:0)
迭代器解决方案如何:
list1 = [['WA', 'WA'], ['DC'], ['HI'], ['NJ', 'NJ', 'NJ', 'NJ', 'NJ'], ['TX', 'TX', 'TX'], ['LA', 'LA'], ['NC'], ['NY'], ['IL', 'IL'], ['GA'], ['MA'], ['AZ']]
list2 = [0.875, 10.875, 0, 0, 0, 0, 0.0, 0.0, 10.0, 0, 0, 0, 0.625, -0.25, 0, 10.0, 0.5, 0, 0, 10.0, 9.25]
f = (x for x in list2) # iterator
list3 = []
for sub in list1:
for i, _ in enumerate(sub):
sub[i] = next(f) # go fetch me the next element of list2
list3.append(sub)
print(list3) # -> [[0.875, 10.875], [0], [0], [0, 0, 0.0, 0.0, 10.0], [0, 0, 0], [0.625, -0.25], [0], [10.0], [0.5, 0], [0], [10.0], [9.25]]**
答案 3 :(得分:0)
尝试使用enumerate
:
list3 = []
for i,j in enumerate(list1):
list3.append(list2[i:i+len(j)])