简体   繁体   中英

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

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
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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