我有这样的列表:
subsets = ["T10", "T12", "T13", "A15", "T23"]
我需要遍历此列表,依次检查T和A,以及是否合并了T&A。
这是我需要的新列表:
newset = ["T10", "T12", "T13, A15", "T23"]
我试图弄清楚如何遍历列表并检查最左边的值。我只需要一个{下一个列表项的字符串的左字符}的表达式-我想!
for i in range(len(subsets)):
if {left char of string for next list item} = "A":
newset.append(subset[i]+", "+ subset[i+1])
i+=1
else:
newset.append(subset[i])
答案 0 :(得分:3)
从您的项目中构建一个新列表,并检查该列表中的最后一个项目是否以T
开头,当前是否以A
开头。如果是这样,请替换新列表中的最后一项:
it = iter(subsets)
result = [next(it)]
for elem in it:
if elem[:1] == 'A' and result[-1][:1] == 'T':
# preceding element is T.., this is A.., combine into a single string
result[-1] = f'{result[-1]}, {elem}'
else:
result.append(elem)
我使用iter()
和next()
来有效地为输出列表添加了第一个元素,从而免去了测试result
是否至少包含一个元素的麻烦。
演示:
>>> subsets = ["T10", "T12", "T13", "A15", "T23"]
>>> it = iter(subsets)
>>> result = [next(it)]
>>> for elem in it:
... if elem[:1] == 'A' and result[-1][:1] == 'T':
... # preceding element is T.., this is A.., combine into a single string
... result[-1] = f'{result[-1]}, {elem}'
... else:
... result.append(elem)
...
>>> result
['T10', 'T12', 'T13, A15', 'T23']
注意:这还会将连续 A*
个元素合并到前面的T
元素中,因此[..., "T13", "A15", "A16", "T17", ...]
会产生[..., "T13, A15, A16", "T17", ...]
。
答案 1 :(得分:1)
这是一种简单的for loop
方法,它会返回一个新列表:
f = []
for item in subsets:
if f and (item[:1], f[-1][:1]) == ('A', 'T'):
f[-1] = '{}, {}'.format(f[-1], item)
else:
f.append(item)
print(f)
['T10', 'T12', 'T13, A15', 'T23']