Python 在分解结构时更改数据类型
以下面的代码为例:Python 在分解结构时更改数据类型,python,destructuring,Python,Destructuring,以下面的代码为例: nums = ["1", "2", "3"] one, two, three = nums print("Sum:", one+two+three) # >> Sum: 123 是否有方法在分解结构时更改字符串的数据类型?我希望下面的方法能奏效,但不幸的是,它没有奏效: nums = ["1", "2", "3"] int(one), int(two), int(three) = nums print("Sum:", one+two+three) # Exp
nums = ["1", "2", "3"]
one, two, three = nums
print("Sum:", one+two+three) # >> Sum: 123
是否有方法在分解结构时更改字符串的数据类型?我希望下面的方法能奏效,但不幸的是,它没有奏效:
nums = ["1", "2", "3"]
int(one), int(two), int(three) = nums
print("Sum:", one+two+three) # Expected output >> Sum: 6
我知道我可以通过执行
one=int(nums[0])
等简单地更改数据类型。。。但我只是想知道在解构赋值表达式本身中是否可以执行类似的操作?您可以执行以下操作map
函数将把作为第一个参数传递的函数应用于列表或iterable中的所有值
注意:map
是惰性的。结果将仅在迭代期间获得。你可以找到更多的细节
现在NUM中的所有值都将是int。您可以执行以下操作
map
函数将把作为第一个参数传递的函数应用于列表或iterable中的所有值
注意:map
是惰性的。结果将仅在迭代期间获得。你可以找到更多的细节
现在NUM中的所有值都将是int。您可以使用内置函数将所有元素转换为int
通过对其应用类型转换函数int
从文档中:
映射(函数、iterable等)返回一个迭代器,该迭代器将函数应用于iterable的每个项,并生成结果 然后可以使用更新的迭代器来分配元素
In [234]: nums = ["1", "2", "3"]
In [235]: one, two, three = map(int,nums)
In [236]: print("Sum:", one+two+three)
Sum: 6
请注意,这与执行以下操作相同,其中我们迭代nums
,并将每个字符串键入int。map
是该操作的简写
In [254]: nums = ["1", "2", "3"]
In [255]: one, two, three = [int(num) for num in nums]
In [256]: print("Sum:", one+two+three)
Sum: 6
您可以使用内置函数将所有元素转换为int
通过对其应用类型转换函数int
从文档中:
映射(函数、iterable等)返回一个迭代器,该迭代器将函数应用于iterable的每个项,并生成结果 然后可以使用更新的迭代器来分配元素
In [234]: nums = ["1", "2", "3"]
In [235]: one, two, three = map(int,nums)
In [236]: print("Sum:", one+two+three)
Sum: 6
请注意,这与执行以下操作相同,其中我们迭代nums
,并将每个字符串键入int。map
是该操作的简写
In [254]: nums = ["1", "2", "3"]
In [255]: one, two, three = [int(num) for num in nums]
In [256]: print("Sum:", one+two+three)
Sum: 6