[英]Splitting .txt of integers into list Python
我正在考慮做谷歌哈希碼,但在實踐問題上遇到了一些問題! 問題是在不超過限制的情況下訂購許多披薩片。 輸入為您提供每種類型的不同切片數量。 這是 c_medium.in 輸入文件:
4500 50
7 12 12 13 14 28 29 29 30 32 32 34 41 45 46 56 61 61 62 63 65 68 76 77 77 92 93 94 97 103 113 114 114 120 135 145 145 149 156 157 160 169 172 179 184 185 189 194 195 195
為了確定我的尺寸選項,我使用了以下代碼:
file = open('c_medium.in','r')
raw_pizza_types = file.readline(2)
pizza_types = raw_pizza_types.split()
print(pizza_types)
max = file.readline(1)
def solution() -> None:
#pizza_types = [int(i) for i in pizza_types] # will loop through strings and convert them to ints
pass
這段代碼應該打印出一個包含不同餡餅上切片數量的列表,而只是簡單地打印出['45']
。 誰能幫我解決這個問題?
readline()
的參數表示要讀取的大小,而不是要讀取的行數。 所以你告訴它只讀取前兩個字符,即 45,然后停止。
您想要做的是使用命令readlines()
,默認情況下,該命令將所有行作為列表讀取。 然后,您只需處理列表中的數據。 我會推薦一些類似的東西:
file = open('filename', 'r')
raw_pizzas = file.readlines()
slices = []
for p in raw_pizzas:
for s in p.split():
slices.append(s)
print(slices)
請注意,這意味着更多的偽代碼,我沒有測試以確保它按編寫的方式工作。
readline
方法的參數是size
並且不讀取第二行,我假設這是您想要做的。 文件句柄是迭代器,除非您seek
. 所以我會按照它們出現在文件中的順序讀入你的變量:
# the with statement is the pythonic way to open files
# since you don't need to remember to close them
with open('c_medium.in','r') as fh:
# read the first line to max, but max itself is a function
# so we will name it something else
maximum_slices = [int(x) for x in next(fh).split()]
# this will split the second line on any whitespace character
pizza_types = next(fh).split()
之后你的列表理解應該是完全足夠的。 我還假設maximum_slices
也應該是一個整數列表
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.