简体   繁体   English

按特定顺序在列表列表中解开元组

[英]Unpacking tuples within a list of lists with specific order

I have a long list of lists. 我的清单很长。 The first item in each list is a tuple with four strings. 每个列表中的第一项是具有四个字符串的元组。 Some of the lists have a second item which is a string: 其中一些列表还有第二个项目,它是一个字符串:

list_one = [('string1', 'number', 'Longstring1', 'long_string2'), 'long_string3']
list_two = [('string5', 'number1', 'Longstring4', 'long_string5')]  

I would like to loop over each of the lists so that the number string is preferably converted to an integer at the beginning of the list and the remaining items in the tuple are their own list items. 我想遍历每个列表,以便最好在列表的开头将数字字符串转换为整数,而元组中的其余项是它们自己的列表项。 If it is not possible to convert the number strings to integers that is okay so long as they are in the first position in the list.So it could hopefully look like this: 如果不可能将数字字符串转换为整数,只要它们在列表的第一位即可,因此希望如下所示:

new_list_one = [number, 'string1', 'Longstring1', 'long_string2', 'long_string3']
new_list_two = [number, 'string5', 'Longstring4', 'long_string5']  

How can I go about unpacking tuples within a specific order? 如何在特定订单中拆包元组? Would it be most simple for me to use a dictionary with the numbers as the key? 使用数字作为关键字的字典对我来说最简单吗? My main problem so far has been distinguishing procedures for lists that have the final string outside of the tuple. 到目前为止,我的主要问题是区分具有在元组之外的最终字符串的列表的过程。

list_one = [('string1', '100', 'Longstring1', 'long_string2'), 'long_string3']
list_two = [('string5', '200', 'Longstring4', 'long_string5')] 

You can unpack the tuple, switch the first and second element, and attempt to convert to and int 您可以打开元组的包装,切换第一个和第二个元素,然后尝试转换为int

def int_if_possible(val):
    try:
        return int(val)
    except ValueError:
        return val

def unpack(l):
    ret = [*l[0], *l[1:]]
    ret[0], ret[1] = int_if_possible(ret[1]), ret[0]
    return ret

print(unpack(list_one))
# [100, 'string1', 'Longstring1', 'long_string2', 'long_string3']
print(unpack(list_two))
# [200, 'string5', 'Longstring4', 'long_string5']

As I understand from you explanation: 据您了解,我的解释是:

  • the second element of the tuple is always an integer 元组的第二个元素始终是整数
  • the tuple has always 4 elements 元组总是有4个元素
  • the list has some times only one more element 列表有时只有一个元素

If these are fixed rules you can be explicit and simple. 如果这些是固定规则,那么您可以明确而简单。

def trans(lst):
    ret = [int(lst[0][1]), lst[0][0], lst[0][2], lst[0][3]]
    if len(lst) == 2:
        ret.append(lst[1])
    return ret

Obs.: the * operator don't work in lists in Python 2.7. 观察: *运算符不适用于Python 2.7中的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM