Python 中单行嵌套 for 循环的问题
Issue with single line nested for loop in Python
我有以字符串形式导出的数据
output = '012345678910abcdefghijkl'
cleaned_output = [output[index:index + 4] for index in range(0, len(output), 4)]
cleaned_output = [cleaned_output[i][item] for i in range(0, len(cleaned_output)) for item in range(0,len(cleaned_output[i]))]
哪个 returns:
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '1', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']
但是,我正在查看下面的 return,关于我哪里出错的任何想法?
[['0', '1', '2', '3'], ['4', '5', '6', '7'], ['8', '9', '1', '0'], ['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]
您应该将输入分成 4 个块,然后将它们直接转换为列表:
cleaned_output = [list(output[i:i+4]) for i in range(0, len(output), 4)]
输出:
[['0', '1', '2', '3'], ['4', '5', '6', '7'], ['8', '9', '1', '0'], ['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]
我有以字符串形式导出的数据
output = '012345678910abcdefghijkl'
cleaned_output = [output[index:index + 4] for index in range(0, len(output), 4)]
cleaned_output = [cleaned_output[i][item] for i in range(0, len(cleaned_output)) for item in range(0,len(cleaned_output[i]))]
哪个 returns:
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '1', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']
但是,我正在查看下面的 return,关于我哪里出错的任何想法?
[['0', '1', '2', '3'], ['4', '5', '6', '7'], ['8', '9', '1', '0'], ['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]
您应该将输入分成 4 个块,然后将它们直接转换为列表:
cleaned_output = [list(output[i:i+4]) for i in range(0, len(output), 4)]
输出:
[['0', '1', '2', '3'], ['4', '5', '6', '7'], ['8', '9', '1', '0'], ['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]