There is data as a list in the tuple. "# The join() is not working properly in the "replace the data divided by split() as a string" part. If you change the elements into strings one by one, it works as you want. I wonder why the list doesn't change to a string.
infile1 = open("a1.txt", "r")
tuple_data = []
title_line = None
idx = 0
while True:
line = infile1.readline()
if not line:
break
else:
line = line.replace("\n", "")
line = line.split(',')
tuple_data.append(line)
won = int(tuple_data[idx][1])
lost = int(tuple_data[idx][2])
# Find the percentage
tuple_data[idx].append(round(won / (won + lost), 3))
idx += 1
print(tuple_data)
infile1.close()
# Sort
tuple_data.sort(key=lambda x: x[3])
print("List in Tuple-------")
print(tuple_data)
# Replace the data divided by split() with a string
idx = 0
for idx in range(len(tuple_data)):
tuple_data[idx] = '\t'.join(tuple_data[idx])
print("String in Tuple-------")
print(tuple_data)
# Write Results
infile2 = open("a2.txt", "w")
# Title line
title_line = "Team\tWon\tLost\trate\n"
infile2.write(title_line)
# Write Sort Data
idx = 0
for idx in range(len(tuple_data)):
infile2.write(tuple_data[idx])
infile2.close()
'\t'.Join
receives a list of strings or tuples and combines them. However, '\t'.In the join(tuple_data[idx])
part, the last element of tuple_data[idx]
is numeric, not a string.
If you read the error message carefully, you can find the answer faster.
© 2024 OneMinuteCode. All rights reserved.