的Python
如何转换网格:
x,x
x,x
到列表列表?:
[['x', 'x'], ['x', 'x']]
答案 0 :(得分:6)
它很简单:
with open(...) as f:
list_of_lists = [line.strip().split(",") for line in f]
# use list_of_lists
答案 1 :(得分:0)
这是获取列表列表的方法:
gridlist = []
f = open('**path/to/file/here**')
for line in f:
a = line.strip().split(',')
gridlist.append(a)
print gridlist
答案 2 :(得分:0)
创建一个函数来遍历每一行并用逗号分隔它们。
def get_gridas_list(filename):
# an empty list to store your data
grid_list = []
# with is the safest way to open a text document
with open(filename, 'r') as file:
# iterate through all the lines in the file
for line in file:
#split is a function associated with strings
# "x,x".split(',') -> ['x', 'x']
grid_list.append(line.strip().split(','))
# return the now full list of lists
return grid_list
答案 3 :(得分:0)
使用文件中的readline,然后使用split-method
list = []
line_from_file = '23wda, wa0dw'
parts = line_from_file.split(', ')
list.append([parts[0], parts[1]])
line_from_file = '234f4fda, wa03d2dw'
parts = line_from_file.split(', ')
list.append([parts[0], parts[1]])
print(list)