我想根据列表(String_list)中找到的字符串元素对成对的整数和字符串元素进行子集化。
String_list = ['I','D','X']
CIG_list = [(65, '='), (1, 'X'), (91, '='), (3, 'D'), (60, '='), (1, 'X'),
(7, '='), (2, 'S')]
然后,我想获取该元素之前的整数元素与该元素的整数之和。
for n in CIG_list:
if n[1] in String_list:
hope=CIG_list[0:(CIG_list.index(n)-1)]
if len(hope) >= 2:
hope = CIG_list[0:(CIG_list.index(n)-1)]
hope4=sum([m[0] for m in hope])
else:
hope = CIG_list[0:(CIG_list.index(n))]
hope4=sum([m[0] for m in hope])
据我所知,此策略无效,因为列表的索引不是唯一的(1,'X')出现了多次。
理想情况下,我将能够获取每个子集的整数与发生切片的位置相关联的字符串的总和。
所需的输出:
[(65, '='), (1, 'X')] , 66 , X
[(65, '='), (1, 'X'), (91, '='), (3, 'D')] , 160 , D
[(65, '='), (1, 'X'), (91, '='), (3, 'D'), (60, '='), (1, 'X')] , 221 , X
答案 0 :(得分:1)
您可以尝试这样。
注意::我刚刚使用了列表理解和enumerate()函数的概念。
.Dispose
输出:
String_list = ['I','D','X']
CIG_list = [(65, '='), (1, 'X'), (91, '='), (3, 'D'), (60, '='), (1, 'X'), (7, '='), (2, 'S')]
for index, tup in enumerate(CIG_list):
ch = CIG_list[index][1]
if ch in String_list:
slice_l = CIG_list[:index + 1] # Used to slice from start to matching point
total = sum([t[0] for t in slice_l]) # 66, 160, 221 etc.
last_char = slice_l[-1][1] # X, D, X etc.
print(slice_l, ",", total, ",", last_char) # Print slice_l, total, last_char