簡體   English   中英

如何將元組轉換為具有浮點和字符串值的列表

[英]How to convert tuple to list with float and string values

我有一個這樣的元組列表:

tuple_list =   [(['MATH120'], 3.665, 0.4737615433949868), (['GER'], 3.4566666666666666, 0.3967146329542181), (['FREE'], 3.415636363636364, 0.450256863026264), ([''], 0.041607963246554365, 0.38832820111766464)]

我想要做的是將其轉換為:

result = [['MATH120', 3.665, 0.4737615433949868],['GER', 3.4566666666666666, 0.3967146329542181],['FREE', 3.415636363636364, 0.450256863026264]]

這意味着我想將它轉換為 3 對的列表並刪除整個元組,如果它內部的列表只有空元素並刪除元組中可能存在的空字符串,例如,如果它是這樣的:

tuple_list = [(['MATH120',''], 3.665, 0.4737615433949868), (['GER','',''], 3.4566666666666666, 0.3967146329542181), (['FREE'], 3.415636363636364, 0.450256863026264), ([''], 0.041607963246554365, 0.38832820111766464)]

我希望它變成和以前一樣:

result = [['MATH120', 3.665, 0.4737615433949868],['GER', 3.4566666666666666, 0.3967146329542181],['FREE', 3.415636363636364, 0.450256863026264]]

我嘗試這樣做是為了將它們放在列表中:

result= [list(map(list, l)) for l in tuple_list]

但由於浮點值,我不斷收到錯誤:

TypeError: 'float' object is not iterable

如果您的數據總是像這樣有規律,並且您只想要內部列表中的第一個元素,那么只需:

 >>> [[x, y, z] for [x, *_], y, z in data] [['MATH120', 3.665, 0.4737615433949868], ['GER', 3.4566666666666666, 0.3967146329542181], ['FREE', 3.415636363636364, 0.450256863026264], ['', 0.041607963246554365, 0.38832820111766464]]

最終編輯:

既然您已經澄清它們是空字符串,我們可以做一些更好的事情:

>>> [ [*filter(None, lst), a, b] for lst, a, b in data if any(lst) ]
[['MATH120', 3.665, 0.4737615433949868], ['GER', 3.4566666666666666, 0.3967146329542181], ['FREE', 3.415636363636364, 0.450256863026264]]
>>>

我實際上認為這是非常好的聲明性

result=  [ [e for e in l if e] + list(t) for l, *t in tuple_list if any(l) ]

[e in t[0] if e]從子列表中刪除空字符串; 然后附加元組的其余元素; 但如果列表中沒有非空元素( any(t[0])False ),則跳過此元組。

您收到此錯誤的原因是因為當您調用map(list, l)時, l指的是內部元組(EG (['MATH120'], 3.665, 0.4737615433949868) ),並且這些浮點數不能直接轉換為列表。 我建議執行以下操作:

for listIndex in range(tuple_list):
    tuple_list[listIndex] = list(tuple_list[listIndex]) # Converts inner tuples to list
    for element in inner_tuple:
        if isinstance(element, list): # checks if element inside tuple is list
            #do logic on list that you need

如果您的第一個元素始終是元組中的列表,則只需以更硬編碼的方式對其進行說明。 它僅適用於與您提供的示例格式相同的數據, list(tuple(list(...), ...), ...)

result_list = []
for x in tuple_list:
    temp_tuple = []
    if (len(x[0]) == 1 and x[0][0] == '') or len(x[0]) == 0:
        continue

    for y in x[0]:
        if y == '':
            continue
        temp_tuple.append(y)

    for y in range(1, len(x)):
        temp_tuple.append(x[y])

    result_list.append(temp_tuple)

我對示例進行了測試和結果,output 就像你問的那樣。

該解決方案不像其他答案那樣是單線解決方案。 但如果可以的話,我個人更喜歡避免 python 中的單行循環。 這使我更容易閱讀它。

你只是多了一層。 用這個:

result = [list(x) for x in tuple_list]

或者

result = list(map(list, tuple_list))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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