请帮助我使用python将['1,7']转换为[1,7]

2024-04-25 19:15:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试过这个

test_list = ['1,7'] 
test_list = [int(i) for i in test_list] 

得到了这个错误

ValueError: invalid literal for int() with base 10: '1,7'

Tags: intestforbase错误withlistint
1条回答
网友
1楼 · 发布于 2024-04-25 19:15:55

您的线路:

test_list = [int(i) for i in test_list] 

正在迭代测试列表中的每个字符串,而不是每个数字。因此,首先需要指向数字字符串,然后是字符串中的数字。为了更好地理解,漫长的路线是:

new = []

for i in test_list: # pointing to the '1,7' string
    for j in i.split(','): # splitting that string into a list
        new.append(int(j)) # appending each split as an int into the new list

print(new) # returns: [1, 7]

有关split()方法here的详细信息

如Epsi95所述,较短的方法是使用一种称为“列表理解”的方法,这是关于here的更多信息。它的实现与上面的for循环相同,只是更整洁、更高效(而且更漂亮):

new = [int(j) for i in ['1,7'] for j in i.split(',')]

相关问题 更多 >

    热门问题