繁体   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