I'm trying to find the smallest number in each string element of my list.
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 ']
I've tried the split() function on each element but the lack of a space in the "6KM" seems to make it work incorrectly.
minVIS = []
for i in range(len(VIS)):
minVIS.append(min(VIS[i].split()))
print(minVIS)
Returns
minVIS = ['10', '10', '10', '10', '10', '10', '10', '10', '10', '10', '10', '10', '10', '10', '10', '10KM,', '10KM,', '10KM,']
Ideally, I'd like
minVis = [10, 10, 10, 6, 6]
for example.
Using Regex. re.findall(r"\\d+", STRING)
get all ints in the string.
Ex:
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)
Output:
[10, 10, 10, 6, 6]
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.