def prepare_for_sort(st):
nums = str(st).split()
for each in nums:
each = int(each)
print(nums)
st是数字类似“20 50 4 8 4 64 6 47 8”的字符串。 Nums必须是整数数组。为什么这不起作用?不能从列表中转换str到int(python)
def prepare_for_sort(st):
nums = str(st).split()
for each in nums:
each = int(each)
print(nums)
st是数字类似“20 50 4 8 4 64 6 47 8”的字符串。 Nums必须是整数数组。为什么这不起作用?不能从列表中转换str到int(python)
这不起作用,因为您的变量each
是对某个对象的引用:首先对同样包含在列表中的对象,然后是对整数对象。然而,each
并没有连接到您想要操作的内容列表。
你可以操纵列表就地:
for index, value in enumerate(nums):
nums[index] = int(value)
或者,您可以创建,而不是一个新的列表:
nums = [int(value) for value in nums]
正如你现在拥有它,你正试图修改值从for循环内部的列表,这是行不通的,因为你只是在for循环内重新分配变量each
。 for循环将简单地丢弃该值,以便将each
分配给列表中的下一个项目。您对each
所做的任何更改都将被丢弃,因为它们完全独立于nums
列表。
你实际上可以用列表理解来实现你的目标。
nums = "20 50 4 8 4 64 6 47 8"
actual_nums = [int(n) for n in nums.split()]
或者如果你真的想在循环中做到这一点。您可以使用循环索引,以便实际修改列表。
for k in range(len(nums)):
nums[k] = int(nums[k]);
如果您可以以任何方式避免它,请不要在循环时修改列表元素。它只会让你陷入麻烦。 相反,试试这个:
def prepare_for_sort(st):
nums = str(st).split()
new_nums = []
for each in nums:
new_nums.append(int(each))
print(new_nums)
或者更短,使用列表理解:
def prepare_for_sort(st):
nums = str(st).split()
new_nums = [int(x) for x in nums]
print(new_nums)
试试这个:
def prepare_for_sort(st):
nums = str(st).split()
arrNums = [int(each) for each in nums]
return arrNums
当然,你需要确保中该函数接收的字符串将始终只有整数和空格。
'st'似乎不是你期望的那样,因为''20 50 4 8 4 64 6 47 8“'至少没有错误作为输入。 Stil并没有做你想做的事情,虽然 – Felk
即使你正在把nums写成一个整数列表,你也不会从'prepare_for_sort'中返回**任何东西,所以你所有的工作都是空话。 –