将.txt整数拆分为列表Python

2024-09-27 22:36:40 发布

您现在位置:Python中文网/ 问答频道 /正文


我正在考虑做Google Hash Code,但在实践问题上遇到了一些问题!问题是订购了很多比萨饼片却没有超过限额。输入为每种类型提供不同数量的切片。这是c_介质。输入文件:

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']。有人能帮我修一下吗


Tags: 代码in类型readline数量rawgooglecode
2条回答

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也应该是一个整数列表

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)

请注意,这意味着更多的伪代码,我还没有测试以确保它能像编写的那样工作

相关问题 更多 >

    热门问题