python - 将 python 列表操作成我想要的字符串类型

标签 python

我有一个嵌套列表,例如:A_board=[['0', '0'],['1', '1']] .我想把这个嵌套列表分开并得到一个结果,如果我调用打印结果,它将显示:< 0 0 > < 1 1 >

我不确定如何用循环来解决这个问题,我首先将矩阵制成列表,方法是:

boardWidth_a=len(A_board)
listLength=len(board[0])

for q in range(0,boardWidth_a):
    for x in range(0, listLength):
        board1D.append(int(board[q][x]));

board1D正在[0, 0, 1, 1]现在,我能对 board1D 做些什么呢?把它变成< 0 0 > < 1 1 >?

最佳答案

似乎有点令人费解——你能不能不这样做:

>>> ' '.join('< {} {} >'.format(*items) for items in A_board)
'< 0 0 > < 1 1 >'

对于 n 元组,调整以下内容:

>>> a = [ [0], [0], [0] ]
>>> fmt = '< {} >'.format
>>> from itertools import chain
>>> fmt(' '.join(map(str, chain.from_iterable(a))))
'< 0 0 0 >'

关于python - 将 python 列表操作成我想要的字符串类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14782192/

相关文章:

python - Python 现在或将来会弃用 `pytz` 吗?

python - Tkinter/Matplotlib 后端冲突导致无限主循环

javascript - 使用 Django Ajax 成功后创建新的 Google map

python - 从 Python 字典中获取任意元素的最快方法是什么?

python - 导入错误 : No module named PytQt5

python - 使用 "infinite"可迭代对象关闭循环时会发生什么?

python - 如何处理Python日志记录中的常规消息?

python - 从递归生成器函数引发异常

python - 如何以高效内存的方式使用 SOAP 水?

python - python 中的因式分解