1

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.

3
  • 4
    norm_list.append((x,y)) Commented Nov 20, 2019 at 7:06
  • 1
    norm_list = [tuple(line.split()[1:3]) for line in norm_file] Commented Nov 20, 2019 at 7:26
  • I want y values to be int. How can I get that done? Commented Nov 20, 2019 at 7:30

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I want y values to be int. How do I get that?
y = int(norm_file_elements[2])
1

Try zip function

It would be much easy

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

2 Comments

I want y values to be int. How can I get that done?
Cast it into int() datatype like int(norm_file_elements[2])
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.