我需要一种方法来读取列表存储在一个文件中的几种不同的方式。我试着考虑用户在文件中存储列表的所有方法,并正确地解释它。你知道吗
下面是一个示例输入文件,其中的列表编写方式不同。你知道吗
# in_file.dat
# List 1 (enclosing brackets, comma separated, spaces after commas)
[0.5, 0.2, 0.6, 0.9, 1.5]
# List 2 (enclosing parenthesis, comma separated, no spaces or some spaces after commas)
(0.5,0.2,0.6,0.9, 1.5)
# List 3 (enclosing keys, mixed commas and semi-colons, mixed no-spaces and spaces)
{0.5,0.2,0.6;0.9;1.5}
# List 4 (single item)
[0.6]
# List 5 (space separated elements)
[2.3 5. 0.6 1.2 0.0 3.1]
应将每一行正确解读为一个列表,从而产生:
ls_1 = [0.5, 0.2, 0.6, 0.9, 1.5]
ls_2 = [0.5, 0.2, 0.6, 0.9, 1.5]
ls_3 = [0.5, 0.2, 0.6, 0.9, 1.5]
ls_4 = [0.6]
ls_5 = [2.3, 5., 0.6, 1.2, 0.0, 3.1]
我阅读文件的通常方式是
# Read data from file.
with open('in_file.dat', "r") as f_dat:
# Iterate through each line in the file.
for line in f_dat:
# Skip comments
if not line.startswith("#") and line.strip() != '':
# Read list stored in line.
ls_X = ??
有什么通用方法可以用来强制python将行解释为列表吗?你知道吗
试试这个:
如果您确定每一行只有一个数字序列,请使用re
希望这就是你要找的。你知道吗
相关问题 更多 >
编程相关推荐