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

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

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种元素的多维(5×6)阵列,可以阅读使用此代码此文件的元素但我不知道如何将它们写入数组。

回答:

为了得到多维数组,你需要逐行读取文件中的行,并用逗号在我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)

回答:

您需要作为字符串来读取数据,并在由逗号和换行符把它分解:

# 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)

回答:

所有你需要的是沿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']

回答:

你可以这样做,使用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]) 

回答:

很多体面的理解基于解决方案的周围。下面是一个使用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)))

回答:

分割每行,就像如果你想为了保持CSV文件的格式,并有一个二维数组,然后可能先设置二维数组,然后遍历文件并添加值可能是要走的路。

array = [] 

for row in range(0,6):

array.append([])

for col in range(0,5):

array[row].append(" ")

print(array)

然后添加你瓦莱斯而不是用空间,导入的文件,通过各行进行迭代,并为每个值在它[`str.split添加到相应的空间,在你的二维数组

以上是 如何在Python中将元素写入数组 的全部内容, 来源链接: utcz.com/qa/264970.html

回到顶部