繁体   English   中英

如何将字符串列表更改为整数列表?

[英]How to change a string list to a list of integers?

我有一个列表,它结合了来自两个来源的输入,最终看起来像下面给出的“pde_fin”。 我需要提取列表中元素的 integer 值以进行进一步处理。 但是,第二组数字似乎给出了一个错误(“invalid literal for int() with base 10:”'1118'")。

pde_fin =['2174', '2053', '2080', '2160', '2065', "'1118'", "'1098'", "'2052'", "'2160'", "'2078'", "'2161'", "'2134'", "'2091'", "'2089'", "'2105'", "'2109'", "'2077'", "'2057'"]
for i in pde_fin:
    print(int(i))

最简单的解决方法是去掉单引号:

for i in pde_fin:
    print(int(i.strip("'")))

使用以下代码更正您的值:

pde_fin =['2174', '2053', '2080', '2160', '2065', "'1118'", "'1098'", "'2052'", "'2160'", "'2078'", "'2161'", "'2134'", "'2091'", "'2089'", "'2105'", "'2109'", "'2077'", "'2057'"]
for i in pde_fin:
    print(int(i.replace("'",'')))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM