Python 如何将列表对转换为元组对
如何通过使用简单编程(例如for loop)将包含对的列表转换为包含元组对的列表?x、 y= 我的代码:Python 如何将列表对转换为元组对,python,Python,如何通过使用简单编程(例如for loop)将包含对的列表转换为包含元组对的列表?x、 y= 我的代码: def read_numbers(): numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90'] numbers.split(',') x,y = tuple numbers return numbers 期望输出: [(68,125), (113,69), (65,86),
def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
numbers.split(',')
x,y = tuple numbers
return numbers
期望输出:
[(68,125), (113,69), (65,86), (108,149), (152,53), (78,90)]
尝试使用嵌套列表理解:
o = [tuple(int(y) for y in x.split(',')) for x in numbers]
[
tuple( # Convert whatever is between these parentheses into a tuple
int(y) # Make y an integer
for y in # Where y is each element in
x.split(",") # x.split(","). Where x is a string and x.split(",") is a list
# where the string is split into a list delimited by a comma.
) for x in numbers # x is each element in numbers
]
尝试使用嵌套列表理解:
o = [tuple(int(y) for y in x.split(',')) for x in numbers]
[
tuple( # Convert whatever is between these parentheses into a tuple
int(y) # Make y an integer
for y in # Where y is each element in
x.split(",") # x.split(","). Where x is a string and x.split(",") is a list
# where the string is split into a list delimited by a comma.
) for x in numbers # x is each element in numbers
]
只需使用列表理解。阅读更多关于它的信息 以下是列表理解的分解和解释(注释):
o = [tuple(int(y) for y in x.split(',')) for x in numbers]
[
tuple( # Convert whatever is between these parentheses into a tuple
int(y) # Make y an integer
for y in # Where y is each element in
x.split(",") # x.split(","). Where x is a string and x.split(",") is a list
# where the string is split into a list delimited by a comma.
) for x in numbers # x is each element in numbers
]
但是,如果您只是为一个列表执行此操作,则无需创建函数。只需使用列表理解即可。阅读更多关于它的信息 以下是列表理解的分解和解释(注释):
o = [tuple(int(y) for y in x.split(',')) for x in numbers]
[
tuple( # Convert whatever is between these parentheses into a tuple
int(y) # Make y an integer
for y in # Where y is each element in
x.split(",") # x.split(","). Where x is a string and x.split(",") is a list
# where the string is split into a list delimited by a comma.
) for x in numbers # x is each element in numbers
]
但是,如果只针对一个列表执行此操作,则无需创建函数。尝试以下操作:
def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
final_list = []
[final_list.append(tuple(int(test_str) for test_str in number.split(','))) for number in numbers]
return final_list
试试这个:
def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
final_list = []
[final_list.append(tuple(int(test_str) for test_str in number.split(','))) for number in numbers]
return final_list
请在网上搜索帐户:如果我在网上找到它,我不会在这里发布:)可能重复的请在网上搜索帐户:如果我在网上找到它,我不会在这里发布:)可能重复的谢谢!成功了!没有map()方法,你怎么能做到这一点呢?谢谢!成功了!如果没有map()方法,您如何做到这一点?您可以省略
元组
构造函数中的[]
括号。无需构建列表
,只需传递生成器表达式即可。您可以省略元组
构造函数中的[]
括号。无需构建列表
,只需传递生成器表达式即可。您可以省略元组
构造函数中的[]
括号。无需构建列表
,只需传递生成器表达式即可。您可以省略元组
构造函数中的[]
括号。无需构建列表
,只需传递生成器表达式即可。