将整数.txt拆分为列表 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也应该是整数列表

最新更新