2024-04-25 19:15:55 发布
网友
我试过这个
test_list = ['1,7'] test_list = [int(i) for i in test_list]
得到了这个错误
ValueError: invalid literal for int() with base 10: '1,7'
您的线路:
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(',')]
您的线路:
正在迭代测试列表中的每个字符串,而不是每个数字。因此,首先需要指向数字字符串,然后是字符串中的数字。为了更好地理解,漫长的路线是:
有关split()方法here的详细信息
如Epsi95所述,较短的方法是使用一种称为“列表理解”的方法,这是关于here的更多信息。它的实现与上面的for循环相同,只是更整洁、更高效(而且更漂亮):
相关问题 更多 >
编程相关推荐