如何在Python 3x中将字符串列表转换为整数列表

时间:2019-03-17 01:40:50

标签: python-3.x string list-comprehension

我正在尝试将字符串格式的数字列表转换为整数。

我尝试了列表理解:marks = [int(x) for x in marks],还尝试了映射:new_list = list(map(int, marks)),但是它们都导致了TypeError

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

完整代码:

size = int(input())
students_and_marks = []
students = []
marks = []

for x in range((size * 2)):
    students_and_marks.append(input())

for x in range(1):
    students.append(students_and_marks[0::2])
    marks.append(students_and_marks[1::2])

new_list = list(map(int, marks))

2 个答案:

答案 0 :(得分:2)

两个代码示例都是正确的。如果您希望将函数应用于列表,则可以使用列表理解,也可以将映射传递给列表构造函数,尽管首选列表理解。

问题出在输入上。具体来说,

marks.append(students_and_marks[1::2])

考虑

>>> a = [1,2,3,4,5]
>>> a[1::2]
[2, 4]

根据您的问题,您不清楚要对切片执行什么操作,即students_and_marks[1::2]。即使marks已经是列表,也可以将其追加到students_and_marks[1::2]

你所做的是

>>> marks = ['1', '2']
>>> nested_marks = []
>>> nested_marks.append(marks)
>>> nested_marks
[['10', '9']]
>>> int(nested_marks)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

虽然我相信您打算这样做,

>>> students_and_marks = ['Linus', '10', 'David', '9']
>>> students = students_and_marks[::2]
>>> students
['Linus', 'David']
>>> marks = students_and_marks[1::2]
>>> marks
['10', '9']
>>> new_marks = [int(mark) for mark in marks]
>>> new_marks
[10, 9]

答案 1 :(得分:0)

在第二个循环中用append()替换两个extend()方法,您就完成了。

  

注意:如果您是初学者,则遵循的策略是好的,否则存在以简单且较少的代码(省时/省时)的最佳方法。

最后,您的代码将如下所示:

size = int(input())
students_and_marks = []
students = []
marks = []

for x in range((size * 2)):
    students_and_marks.append(input())

print(students_and_marks)
for x in range(1):
    students.extend(students_and_marks[0::2])
    marks.extend(students_and_marks[1::2])

print(marks)                     # ['R A', '2', 'K T', '4', 'P K', '6']
new_list = list(map(int, marks)) # ['2', '4', '6']
print(new_list)                  # [2, 4, 6]
  

端子输入和输出

Rishikeshs-MacBook-Air:PythonCode hygull$ python3 stk_prob_str.py 
3
R A
2
K T
4
P K
6
['R A', '2', 'K T', '4', 'P K', '6']
['2', '4', '6']
[2, 4, 6]