这可能是一个重复的问题,但我想知道有没有办法解压缩列表列表并从解压缩的结果中创建一个变量?我在文件中有一个数据,例如:
'[416213688, 422393399, 190690902, 81688],| [94925847, 61605626, 346027022],| [1035022, 1036527, 1038016]'
所以我打开一个文件并将其列为列表
with open ('data.txt', "r") as f:
a = f.read()
a = a.split("|")
print(*a)
输出:
[416213688, 422393399, 190690902, 81688], [94925847, 61605626, 346027022], [1035022, 1036527, 1038016]
这是我程序下一步需要的输出。但是我不能使这个结果a
变量进一步使用它。SyntaxError: can't use starred expression here
如果我尝试,它会给我一个:
a = (*a)
我尝试使用 来制作它zip
,但它给了我不正确的输出,类似于问题zip 函数给出不正确的输出中描述的内容。
<zip object at 0x0000000001C86108>
那么有什么方法可以解压缩列表并获得如下输出:
[1st list of variables], [2nd list of variables], [etc...]
如果我使用 itertools 我得到:
l = list(chain(*a))
Out: ['[', '4', '1', '6', '2', '1', '3', '6'...
这不是必需的
所以工作选项是https://stackoverflow.com/a/46146432/8589220:
row_strings = a.split(",| ")
grid = [[int(s) for s in row[1:-1].split(", ")] for row in row_strings]
print(",".join(map(str, grid)))