[英]Python converting list of strings to list of integers
hi I'm trying to convert this list of strings: lists=['111,222','121,121']
into a list of integers but keep running into errors, any advice would be helpful.嗨,我正在尝试将此字符串
lists=['111,222','121,121']
: lists=['111,222','121,121']
转换为整数列表,但不断遇到错误,任何建议都会有所帮助。 I've tried:我试过了:
results=[int(i) for i in lists]
print(results)
but keep getting "invalid literal for int() with base 10: '111,222'"但不断收到“以 10 为基数的 int() 的无效文字:'111,222'”
You need to remove the commas, for example:您需要删除逗号,例如:
lists=['111,222','121,121']
result = [int(s.replace(',', '')) for s in lists]
print(result)
Output输出
[111222, 121121]
This should work这应该工作
import re
lists=['111,222','121,121']
results = [ int("".join(re.findall('[0-9]+', element))) for element in lists ]
# results = [111222, 121121]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.