簡體   English   中英

如何將列表對轉換為元組對

[英]How to convert list pairs into tuple pairs

如何通過使用簡單的編程(例如for循環)將包含對的列表轉換為包含元組對的列表? 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)]
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]

只需使用列表理解即可。 在這里閱讀更多信息!

# 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
]

但是,如果僅對一個列表進行操作,則無需創建函數。

嘗試這個 :

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM