, 당신은 사용 튜플의 목록에 파일에서 읽을 수 있습니다
# generator to read file and return each line as a list of values
pairs = (line.split() for line in open("x.txt"))
# use list comprehension to produce a list of tuples
fruits = [(name, float(price)) for name, price in pairs]
print fruits
# will print [('apples', 1.23), ('pears', 231.23), ('guava', 12.3)]
float()
은 두 번째 값 (price
)을 str에서 부동 소수점 숫자로 변환하는 데 사용되었습니다.
참조 : list comprehension 및 generator expression.
당신은 DICT에 튜플의 목록을 변환 할 수 있습니다, 쉽게 각 과일의 가격을 조회 할 수 있도록 :
price_lookup = dict(fruits)
print price_lookup["apples"]
# will print 1.23
print price_lookup["guava"] * 2
# will print 24.6
참조 : dict()
합니다.
입력 파일에 몇 가지 예제 라인을 줄 수 있습니까? 형식 지정이 매우 모호합니다. –
그렇지 않습니다. 잘 이해할 수 있습니다. 텍스트 파일이 있습니다. 줄마다 두 개의 공백으로 구분 된 값 (문자열과 숫자)이 있습니다. 그는 파이썬이 두 번째 필드를 문자열 대신 숫자로 읽길 원합니다. –
@ H2CO3 : 우주로 분리 된 것을 어떻게 알 수 있습니까? aix는 쉼표로 해석했다. 또한 Excel에서 내 보낸 CSV 파일 일 수도 있으므로 따옴표 등을 처리해야합니다. –