所以我有一个清单:
['13:57:09.273 0,Type=IsXover Count=4,mcuTs=0x000265C7,lp-isD=1',
'13:57:09.341 1,Type=Xover Count=47,mcuTs=0x0002660A,lp-isD=0',
'13:57:15.389 0,Type=Xover Count=48,mcuTs=0x00027D87,lp-isD=1']
我想做的事情就像在每个元素中查找'over'然后打印从'over'开始直到下一个逗号的字符串。所以结果应该是这样的:
['over Count=4','over Count=47','over Count=48']
如果我直接从文件中读取,我可以使用'rfind()'来执行此操作,但由于列表没有'rfind()',我想知道是否有其他方法可以执行此操作?
答案 0 :(得分:2)
一种简单的方法是:
list = ['13:57:09.273 0,Type=IsXover Count=4,mcuTs=0x000265C7,lp-isD=1',
'13:57:09.341 1,Type=Xover Count=47,mcuTs=0x0002660A,lp-isD=0',
'13:57:15.389 0,Type=Xover Count=48,mcuTs=0x00027D87,lp-isD=1']
result = []
for string in list:
for index, sub_string in enumerate(string.split(',')):
if index == 1:
result.append(sub_string[sub_string.find('over'):])
print(result)
此代码的列表理解版本不像上面的代码那样可读,但在这里它是两种方式:
result = [sub_string[sub_string.find('over'):] for string in list for index, sub_string in enumerate(sub_string.split(',')) if index == 1]
print(result)
两个代码段都会提供所需的
结果['over Count=4','over Count=47','over Count=48']
答案 1 :(得分:0)
您可以使用正则表达式来解决问题:
import re
Structure = ['13:57:09.273 0,Type=IsXover Count=4,mcuTs=0x000265C7,lp-isD=1',
'13:57:09.341 1,Type=Xover Count=47,mcuTs=0x0002660A,lp-isD=0',
'13:57:15.389 0,Type=Xover Count=48,mcuTs=0x00027D87,lp-isD=1']
Counts = []
for element in Structure:
sub_array = element.split(",")
valid = re.match(r"^.*(over Count=(\d+))", sub_array[1].strip())
Counts.append(valid.group(1))
print(Counts)
哪个会打印:
['over Count=4', 'over Count=47', 'over Count=48']
答案 2 :(得分:0)
不使用正则表达式,我们可以使用字符串方法:
a = ['13:57:09.273 0,Type=IsXover Count=4,mcuTs=0x000265C7,lp-isD=1',
'13:57:09.341 1,Type=Xover Count=47,mcuTs=0x0002660A,lp-isD=0',
'13:57:15.389 0,Type=Xover Count=48,mcuTs=0x00027D87,lp-isD=1']
b = []
for s in a:
i1 = s.find('over')
i2 = s.find(',', i1)
b.append(s[i1:i2])
print(b)
给出
['over Count=4', 'over Count=47', 'over Count=48']
或者,如果你想要一行列表理解:
[s[s.find('over'):s.find(',', s.find('over'))] for s in a]
这里的技巧是字符串的find
方法返回给定子字符串开头的索引,如果我们提供第二个参数,则搜索从该整数开始。
答案 3 :(得分:0)
这可以帮助你
itemList = ['13:57:09.273 0,Type=IsXover Count=4,mcuTs=0x000265C7,lp-isD=1',
'13:57:09.341 1,Type=Xover Count=47,mcuTs=0x0002660A,lp-isD=0',
'13:57:15.389 0,Type=Xover Count=48,mcuTs=0x00027D87,lp-isD=1']
for item in itemList:
if ‘over’ in item:
indexi = item.find(‘over’)
indexy = item.find(‘,mcuTs’)
print(item[indexi:indexy]
答案 4 :(得分:0)
您可以使用split
两次,并将结果与over
:
inList = ['13:57:09.273 0,Type=IsXover Count=4,mcuTs=0x000265C7,lp-isD=1',
'13:57:09.341 1,Type=Xover Count=47,mcuTs=0x0002660A,lp-isD=0',
'13:57:15.389 0,Type=Xover Count=48,mcuTs=0x00027D87,lp-isD=1']
newList = ['over' + elem.split(',')[1].split('over')[1] for elem in inList]
print(newList)
输出:
['over Count=4', 'over Count=47', 'over Count=48']