튜플안 리스트를 문자열로 바꾸기

조회수 788회

튜플안에 리스트로 데이터가 있습니다. "# split()으로 나누었던 데이터를 문자열로 바꿈" 부분에 join()이 제대로 작동을 안하네요. 요소를 하나하나 문자열로 바꿔서 붙이면 원하는데로 작동은 되는데요. 리스트가 왜 문자열로 안바뀌는지 궁금합니다.


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

        # 퍼센트 구하기
        tuple_data[idx].append(round(won / (won + lost), 3))

        idx += 1

print(tuple_data)

infile1.close()

# 정렬
tuple_data.sort(key=lambda x: x[3])

print("List in Tuple-------")
print(tuple_data)

# split()으로 나누었던 데이터를 문자열로 바꿈
idx = 0
for idx in range(len(tuple_data)):
    tuple_data[idx] = '\t'.join(tuple_data[idx])

print("String in Tuple-------")
print(tuple_data)

# 결과 쓰기
infile2 = open("a2.txt", "w")

# 제목줄
title_line = "Team\tWon\tLost\trate\n"
infile2.write(title_line)

# Sort한 데이터 쓰기
idx = 0
for idx in range(len(tuple_data)):
    infile2.write(tuple_data[idx])

infile2.close()

1 답변

  • 좋아요

    1

    싫어요
    채택 취소하기

    '\t'.join 은 스트링의 리스트나 튜플 등을 받아서 합쳐줍니다. 그러나, '\t'.join(tuple_data[idx]) 부분에서 tuple_data[idx] 의 마지막 원소가 문자열이 아닌 숫자형입니다.

    에러메시지를 잘 읽어보시면, 더 빨리 답을 찾을 수도 있어요.

    • 우왓 먼저 문자열로 바꾸고 join()해주니 잘 되네요. 감사합니다. Jinn Park 2019.5.24 13:25

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)