【问题标题】:Looping over N lines of a file and storing in multipel lists循环文件的 N 行并存储在多个列表中
【发布时间】:2016-11-23 18:16:02
【问题描述】:

我有一个大文件(大约 80,000 行),我想将每个 10 行块存储到一个单独的列表中。对于前三个 10 行块,我有:

N=10 #Number of lines per block

with open("file", "r") as myfile:
        profile1 = list(islice(myfile, 0,N))
        profile2 = list(islice(myfile, 0,N))
        profile3 = list(islice(myfile, 0,N))

我希望有数百个这样的 10 行块,所以这显然不是一个很好的方法。

如何将列表生成和islice 函数合并到一个循环中?

提前谢谢你!

【问题讨论】:

  • 创建 profile=[]append 新列表
  • 那不会只创建一个名为“profile”的列表并导致所有内容都存储在其中吗?
  • 是的,但是你知道索引 0 是 profile1,1 是 profile2,等等,这适用于不同的文件长度
  • 感谢您的帮助,但我最终需要将它们作为单独的列表。
  • profile 将是一个列表列表,你需要做什么?

标签: python list loops itertools


【解决方案1】:

使用以下内容:

with open('file', 'r') as f:
    lines = f.readlines()
chunks = [lines[item:item+10] for item in range(0, len(lines), 10)]  # with Python 2 you can use xrange instead of range for large lists

要将每个块转换为数组,请尝试以下操作:

import numpy as np

my_arrays = [np.asarray(chunk) for chunk in chunks]

【讨论】:

  • 将第一个块变成我试过的数组: set1=np.genfromtxt(chunks[0], skip_header=2,usecols=[1,2,3]) 我可以做类似的事情吗一个循环来制作所有的块数组?
【解决方案2】:

你可以试试这个:

import numpy as np

# read the file in lines
with open('file.txt','r') as f:
    lines = f.read().splitlines()

# use a list comprehension to split your list in chunks of 10
list_of_lists = [lines[i:i + 10] for i in xrange(0, len(lines), 10)]

# 1st chunks of 10 
print list_of_lists[0]
# 4th chunks of 10
print list_of_lists[3]

# update - turn into arrays
list_of_arrays = []
for i in list_of_lists:
    arr = np.asarray(i)
    list_of_arrays.append(arr)

【讨论】:

  • 有没有办法遍历每个子列表以使每个子列表成为自己的数组?
猜你喜欢
  • 2021-11-04
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
  • 2020-05-04
相关资源
最近更新 更多