如何在Python中将数组写入数组

问题描述 投票:0回答:6

我从txt文件中读取元素,我想将数据写入数组,我知道我必须使用substring方法,但我不知道如何在使用substring方法时生成数组。

example.txt文件包含

001, A, 50, 70, 65
002, B, 25, 55, 80
003, C, 60, 40, 85
004, D, 75, 55, 70
005, E, 40, 40, 45
006, F, 35, 25, 85

我的python代码:

file = open("example.txt", "r")
a = file.read()
print(a)

我需要生成30个元素多维(5x6)数组,我可以使用此代码读取此文件的元素,但我想知道如何将它们写入数组。

python arrays string
6个回答
2
投票

要获得多维数组,您需要逐行读取文件,并用逗号分隔每一行,例如在我的previous answer

# Prepare result array:
array = []
# Open file
with open("example.txt", "r") as f:
    # read the contents of file line by line:
    for line in f:
        # split current line by comma to get array of items from it
        array_parts = line.split(",")
        # filter elements, removing empty, and stripping spaces:
        array_parts = [item.strip() for item in array_parts if item.strip() != ""]
        # add line's items into result array:
        array.append(array_parts)        
# Printing result:
print(array)

3
投票

你可以这样做,使用split

In [14]: print map(str.strip,sum([i.split(',') for i in open("example.txt").split('\n')],[]))
['001', 'A', '50', '70', '65', '002', 'B', '25', '55', '80', '003', 'C', '60', '40', '85', '004', 'D', '75', '55', '70', '005', 'E', '40', '40', '45', '006', 'F', '35', '25', '85']

用不同方法拼合列表,

result = map(str.strip,[item for sublist in [i.split(',') for i in txt.split('\n')] for item in sublist])

2
投票

所有你需要的是str.split()str.strip()

with open("example.txt") as f:
    my_list = [w.strip() for l in f for w in l.split(',')]
#                ^ to remove extra white-spaces 

这将返回你my_list列表为:

>>> my_list
['001', 'A', '50', '70', '65', '002', 'B', '25', '55', '80', '003', 'C', '60', '40', '85', '004', 'D', '75', '55', '70', '005', 'E', '40', '40', '45', '006', 'F', '35', '25', '85']

2
投票

大量基于理解的解决方案。这是一个使用mapitertools.chain

from itertools import chain
with open("example.txt", "r") as f:
    array = list(chain(*(map(str.strip, line.split()) for line in f)))

1
投票

您需要将数据作为字符串读取,并在用逗号和换行符分割时:

# Open file
with open("example.txt", "r") as f:
    # read the contents and replace "\n" characters by commas
    thedata = f.read().replace("\n", ",")
    # split it by "," creating an array
    array = thedata.split(",")
    # if it's needed, remove empty elements and trim spaces:
    array = [item.strip() for item in array if item.strip() != ""]
# Printing result:
print(array)

0
投票

如果你想保留CSV文件的格式并拥有一个二维数组,那么可能先设置2d数组然后遍历文件并添加值可能是要走的路。

array = []

for row in range(0,6):
    array.append([])
    for col in range(0,5):
        array[row].append(" ")

print(array)

然后添加值而不是空格,导入文件,遍历每一行,并为每个值将其添加到二维数组中的相应空间

© www.soinside.com 2019 - 2024. All rights reserved.