[英]How to convert list pairs into tuple pairs
How do you turn a list that contain pairs into a list that contains tuple pairs by using easy programming eg for loop? 如何通过使用简单的编程(例如for循环)将包含对的列表转换为包含元组对的列表? x,y = ...?
x,y = ...?
My code: 我的代码:
def read_numbers():
numbers = ['68,125', '113,69', '65,86', '108,149', '152,53', '78,90']
numbers.split(',')
x,y = tuple numbers
return numbers
desire output: 需求输出:
[(68,125), (113,69), (65,86), (108,149), (152,53), (78,90)]
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]
通过使用嵌套列表理解来尝试此操作:
o = [tuple(int(y) for y in x.split(',')) for x in numbers]
Just use list comprehension. 只需使用列表理解即可。 Read more about it 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]
Here is a breakdown and explanation (in comments) of the list comprehension: 这是列表理解的细分和解释(用注释):
[
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
]
However, if you are just doing it for one list, there is no need to create a function. 但是,如果仅对一个列表进行操作,则无需创建函数。
Try this : 尝试这个 :
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.