我试图在列表的每个字符串元素中找到最小的数字。
VIS = ['GREATER THAN 10 KM ', 'GREATER THAN 10 KM ', 'GREATER THAN 10 KM ', '10 KM, REDUCING TO 6KM, IN PASSING SHOWERS ', '10 KM, REDUCING TO 6KM, IN PASSING SHOWERS ']
我已经在每个元素上尝试了split()函数,但是“ 6KM”中缺少空格似乎使它无法正常工作。
minVIS = []
for i in range(len(VIS)):
minVIS.append(min(VIS[i].split()))
print(minVIS)
返回
minVIS = ['10', '10', '10', '10', '10', '10', '10', '10', '10', '10', '10', '10', '10', '10', '10', '10KM,', '10KM,', '10KM,']
理想情况下,我想要
minVis = [10, 10, 10, 6, 6]
例如。
答案 0 :(得分:1)
使用正则表达式。 re.findall(r"\d+", STRING)
获取字符串中的所有整数。
例如:
import re
VIS = ['GREATER THAN 10 KM ', 'GREATER THAN 10 KM ', 'GREATER THAN 10 KM ', '10 KM, REDUCING TO 6KM, IN PASSING SHOWERS ', '10 KM, REDUCING TO 6KM, IN PASSING SHOWERS ']
minVIS = []
for i in VIS:
minVIS.append(min(map(int, re.findall(r"\d+", i))))
#If floats in string Thanks Anton vBR
#minVIS.append(min(map(float, re.findall(r"\d+\.?\d*", i))))
print(minVIS)
输出:
[10, 10, 10, 6, 6]
答案 1 :(得分:0)
import re
VIS = ['GREATER THAN 10 KM ', 'GREATER THAN 10 KM ', 'GREATER THAN 10 KM ', '10 KM, REDUCING TO 6KM, IN PASSING SHOWERS ', '10 KM, REDUCING TO 6KM, IN PASSING SHOWERS ']
print (list((min(map(int, re.findall(r'\d+', item)))) for item in VIS))
otuput:
[10, 10, 10, 6, 6]
from itertools import groupby
result = []
for item in VIS:
result.append(min([int(''.join(i)) for is_digit, i in groupby(item, str.isdigit) if is_digit]))
print (result)
。
# equal with list comprehension
print ([min([int(''.join(i)) for is_digit, i in groupby(item, str.isdigit) if is_digit]) for item in VIS])
otuput:
[10, 10, 10, 6, 6]