[英]Extract and round numbers from list of strings in Python
我有一个包含字符串、整数和浮点数的 Python 列表
my_list = [['100', '200.1', 'z', '300.9', '400', '100.2']]
我一直在试图弄清楚如何:
目标是返回一个类似于下面列表的列表
new_list = [100, 200, 301, 400]
这可能吗?我应该如何处理?
删除任何字母数字并将 rest 转换为舍入整数的最安全方法如下所示:
import re
my_list = [['100', '200.1', 'z', '1000_100', '300.9', '400', '100.2']]
my_list_2 = list(set([round(float(x)) for x in my_list[0] if re.fullmatch("[\d\.]+",x) is not None]))
print(my_list_2)
[200、400、100、301]
感谢 Alexander 和 Stefan,一个大大改进的答案。
请注意,您的问题有一个包含字符串列表的列表。
如果您实际上有一个字符串列表,请省略[0]
。
result = []
for item in my_list[0]:
try:
v = float(item)
except ValueError:
continue
v = int(round(v))
if v not in result:
result.append(v)
然后
print(result)
[100, 200, 301, 400]
最简单的方法是创建一个帮助器 function ,它可以让您在不抛出的情况下转换为 int:
my_list = [['100', '200.1', 'z', '300.9', '400', '100.2']]
def make_int(s):
"""
Convert s to an int, rounding if it is a floating point value.
Return None if the conversion cannot be done.
"""
try:
return int(round(float(s)))
except:
return None
newlist = list(set([i for i in [make_int(s) for s in my_list[0]] if i != None]))
这涉及两个嵌套列表推导:
内部将列表转换为四舍五入的浮点数,为字符串返回None
: [make_int(s) for s in my_list[0]]
外层去掉None
的: [i for i in <inner> if i != None]
这也消除了使用正则表达式的需要。
这是一个班轮
list(dict.fromkeys(x for x in (round_or_none(s) for s in l) if x))
(当然,如果您事先定义了round_or_none
function,
def round_or_none(s):
try:
return round(float(s))
except ValueError:
pass
那是:-)
演示:
>>> def round_or_none(s):
... try:
... return round(float(s))
... except ValueError:
... pass
...
>>> l = ['100', '200.1', 'z', '300.9', '400', '100.2']
>>> list(dict.fromkeys(x for x in (round_or_none(s) for s in l) if x))
[100, 200, 301, 400]
>>>
没有额外的 function
rounded = []
for s in l:
try:
rounded.append(round(float(s)))
except ValueError:
pass
rounded = list(dict.fromkeys(rounded))
这适用于 Python 3.6 和更新版本,否则使用 OrderedDict
from collections import OrderedDict
...
rounded = list(OrderedDict.fromkeys(rounded))
另一种方法:使用more-itertools 。
from more-itertools import map_except, unique_everseen
my_list = ['100', '200.1', 'z', '300.9', '400', '100.2']
intlist = list(unique_everseen(map_except(lambda s: round(float(s)), my_list, ValueError)))
##########################################################################################
print(intlist) #> [100, 200, 301, 400]
这是文档
最简单的方法是使用“try/catch”并从中构建新列表。
my_list = ['100', '200.1', 'z', '300.9', '400', '100.2']
new_list = []
for item in my_list:
try:
new_list.append(int(float(item)))
except ValueError:
pass
new_list = list(set(new_list))
print(new_list)
另一种方法是使用列表推导。 如果您想要舍入而不是截断,请使用round
而不是int
。
“pythonic”单线:
a = ['100', '200.1', 'z', '300.9', '400', '100.2']
list(set([int(round(float(b))) for b in a if b.isdigit()]))
>>> [400, 100]
简单的答案
my_list = [['100', '200.1', 'z', '300.9', '400', '100.2']]
new_list=[]
for i in my_list:
for j in i:
try:
num=round(float(j))
if num not in new_list:
new_list.append(num)
except:
pass
print(new_list)
嗯,为了解决这个问题,我会使用一些技巧和列表理解。
#with a regex you can define a matching pattern in order to
#clean the list of strings of every alpabetic element
import re
old = ['100', '200.1', 'z', '300.9', '400', '100.2']
# for every element that not match with capitals A to Z, or a to z
# make it a round float into this list.
new = [round(float(x)) for x in old if not re.match(r'[A-Za-z]',x)]
#clean the duplicates and print
print(list(set(new)))
真的。 我首先错过了浮动转换 - 不应该回答电话中的问题:) 已修复
列表的格式没有明确定义。 为了这个解决方案,我假设输入是一个二维的字符串列表(也就是字符串列表)。 如果您的列表遵循不同的格式(多层次深度、与字符串混合的子列表等),则列表可能不是您需要的数据结构。
import itertools as itt
def str_to_int(str_in):
try:
res = round(float(str_in))
except ValueError:
res = None
return res
def trans_lst(lst_in):
flat_lst = itt.chain.from_iterable(lst_in)
parse_res = (str_to_int(item) for item in flat_lst)
res_lst = list(set((item for item in parse_res if item is not None)))
return res_lst
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.