【发布时间】:2021-06-10 07:58:43
【问题描述】:
我有以下清单:
lst=['(9971, 18847)',
'(9971, 19188)',
'(9972, 18282)',
'(9977, 19201)',
'(9989, 18635)',
'(9993, 18225)',
'(9996, 19099)',
'(9997, 18178)',
'(10000, 18266)']
我想将列表中的每个元素从 str 转换为 int。我该怎么做?
到目前为止我尝试了什么?
op=[]
for i in lst:
new_lst=int(lst[i])
op.append(new_lst)
我收到以下错误ValueError: invalid literal for int() with base 10:。我该如何解决?
【问题讨论】:
-
由于这些字符串中不仅仅是一个 int,您希望结果看起来像什么?
-
import ast; op = list(map(ast.literal_eval, lst))应该这样做…… -
我认为问题出在上游:您是如何获得这份清单的?您应该尝试直接获取数字而不是字符串,因此您不需要在之后使用
eval()
标签: python string list integer