我有一个列表元素列表,因为我必须访问特定的数字元素并使用python代码合并它们。
我尝试使用列表理解,但无法正常工作。
myList = [['a:', 'b:', '4,80', 'c:', 'b:', '5,00', ':', '4,91', 'Pass'], ['a:', 'b:', '1,45', 'c:', 'b:', '1,55', 'd:', '1,51', 'Pass'], ['a:', 'b:', '-1,15', 'a:', 'b:', '-0,95', 'c:', '-1,07', 'Pass']]
test = [myList [i] for i in [2,5,7]]
str1 = ''.join(test)
remove = int(str1.replace(',',''))
add_commas= "{:,}".format(remove)
conv_list = add_commas.split(',')
ac,ll,ut = conv_list[0],conv_list[1],conv_list[2]
print(ac,ll,ut)
预期输出应为:
[[480,500,491],[145,155,151],[-115,-095,-107]]
答案 0 :(得分:1)
如果只收集所需的字符,则可以使用以下函数将其返回:
GOOD_CHARS = set('0123456789-+')
def to_number(num_str):
return ''.join(c for c in num_str if c in GOOD_CHARS)
然后,如果您丢弃任何空字符串,您将得到您想要的。
my_list = [['a:', 'b:', '4,80', 'c:', 'b:', '5,00', ':', '4,91', 'Pass'],
['a:', 'b:', '1,45', 'c:', 'b:', '1,55', 'd:', '1,51', 'Pass'],
['a:', 'b:', '-1,15', 'a:', 'b:', '-0,95', 'c:', '-1,07', 'Pass']]
print([[int(to_number(x)) for x in row if to_number(x)] for row in my_list])
[[480, 500, 491], [145, 155, 151], [-115, -95, -107]]
答案 1 :(得分:1)
myList = [['a:', 'b:', '4,80', 'c:', 'b:', '5,00', ':', '4,91', 'Pass'],
['a:', 'b:', '1,45', 'c:', 'b:', '1,55', 'd:', '1,51', 'Pass'],
['a:', 'b:', '-1,15', 'a:', 'b:', '-0,95', 'c:', '-1,07', 'Pass']]
result= []
for sub_lst in myList:
res=[]
for i in sub_lst:
if i.__contains__(','):
res.append(int(i.replace(",","")))
result.append(res)
print(result)
#[[480, 500, 491], [145, 155, 151], [-115, -95, -107]]
答案 2 :(得分:1)
使用re
模块的一种可能的解决方案:
myList = [['a:', 'b:', '4,80', 'c:', 'b:', '5,00', ':', '4,91', 'Pass'],
['a:', 'b:', '1,45', 'c:', 'b:', '1,55', 'd:', '1,51', 'Pass'],
['a:', 'b:', '-1,15', 'a:', 'b:', '-0,95', 'c:', '-1,07', 'Pass']]
import re
r = re.compile(r'[\d\-+]+')
out = [[int(i) for i in (''.join(r.findall(d)) for d in row) if i] for row in myList]
from pprint import pprint
pprint(out, width=30)
打印:
[[480, 500, 491],
[145, 155, 151],
[-115, -95, -107]]
答案 3 :(得分:0)
使用isdigit()
字符串方法检查数字,然后执行int()
将其转换为数字
In [1]: myList = [['a:', 'b:', '4,80', 'c:', 'b:', '5,00', ':', '4,91', 'Pass'], ['a:', 'b
...: :', '1,45', 'c:', 'b:', '1,55', 'd:', '1,51', 'Pass'], ['a:', 'b:', '-1,15', 'a:',
...: 'b:', '-0,95', 'c:', '-1,07', 'Pass']]
In [2]: out = [[int(j.replace(',', '')) for j in i if j.replace(',', '').isdigit()] for i
...: in myList]
In [3]: out
Out[3]: [[480, 500, 491], [145, 155, 151], []]