B.T
B.T

Reputation: 57

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.

Upvotes: 1

Views: 381

Answers (3)

Ajax1234
Ajax1234

Reputation: 71451

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')]

Upvotes: 1

Sapan Zaveri
Sapan Zaveri

Reputation: 518

Try zip function

It would be much easy

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

Upvotes: 1

Teemu Kurppa
Teemu Kurppa

Reputation: 4839

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)

Upvotes: 1

Related Questions