简体   繁体   中英

Python: Create a list of tuples

I want to create a list of tuples and have this table:

Nr  Name        Value   F/R
1   6347_sx     123.98  F
2   hff_475     234.99  F
3   sjdh_65     123.67  R
4   6347_sx     345.12  R

And I want a list like this:

norm_list = [('6347_sx',123.98), ('hff_475',234.99), ('sjdh_65',123.67), ('6347_sx',345.12)] 

I try this but it did not give me the desired output:

norm_file = open("table.txt")

norm_list = []

for norm_line in norm_file.readlines():
    norm_file_elements = norm_line.split()

    x = norm_file_elements[1]
    y = norm_file_elements[2]
    norm_list= [(x,y)]
    print(norm_list)

y values have to be int. Thank you for any help.

You need to append element to the list inside the loop. In your code example, you are always setting the variable to a list of a single element, instead of appending.

Thus, change your code as follows:

norm_file = open("table.txt")

norm_list = []

for norm_line in norm_file.readlines():
    norm_file_elements = norm_line.split()

    x = norm_file_elements[1]
    y = norm_file_elements[2]
    norm_list.append((x,y))
print(norm_list)

Try zip function

It would be much easy

print(list(zip(norm_file_elements[1], norm_file_elements[2]))

You can use re.findall :

s = """
Nr  Name        Value   F/R
1   6347_sx     123.98  F
2   hff_475     234.99  F
3   sjdh_65     123.67  R
4   6347_sx     345.12  R
"""
d = re.findall('\w+_\w+|\d+\.\d+', s)
result = [(d[i], d[i+1]) for i in range(0, len(d), 2)]

Output:

[('6347_sx', '123.98'), ('hff_475', '234.99'), ('sjdh_65', '123.67'), ('6347_sx', '345.12')]

You can also use re.split with unpacking:

t = list(filter(None, s.split('\n')))
_, *data = [(a, b) for _, a, b, _ in map(lambda x:re.split('\s+', x), t)]

Output:

[('6347_sx', '123.98'), ('hff_475', '234.99'), ('sjdh_65', '123.67'), ('6347_sx', '345.12')]

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