如何使用简单的编程(如循环)将包含对的列表转换为包含元组对的列表? 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), (108,149), (152,53), (78,90)]
答案 0 :(得分:2)
def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
return [tuple(map(int,pair.split(','))) for pair in numbers]
答案 1 :(得分:2)
使用嵌套列表理解来尝试:
o = [tuple(int(y) for y in x.split(',')) for x in numbers]
答案 2 :(得分:1)
只需使用列表理解。阅读更多相关信息here!
# Pass in numbers as an argument so that it will work
# for more than 1 list.
def read_numbers(numbers):
return [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
]
但是,如果您只是为一个列表执行此操作,则无需创建函数。
答案 3 :(得分:0)
试试这个:
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