我有一个整数,看起来像这样
a = 1010101010010100我想变成这样的东西
list = [[1,0,1,0],[1,0,1,0],[1,0,0,1],[0,1,0,0]]我尝试做的事情是这样的
b = str(a)
list1 = [];
for x in b:
if b.index(x)==0:
tmp_list = [];
if b.index(x)!=0%3:
tmp_list.append(x):
if b.index(x)==0%3 & b.index(x)!=0:
list1.append(tmp_list)
tmp_list=[]; 我没有得到预期的结果。
发布于 2015-07-04 00:22:57
如果你想把你的序列分成4个一组,你可以简单地这样做:
>>> b='1010101010010100'
>>> [b[i:i+4] for i in range(0, len(b), 4)]
['1010', '1010', '1001', '0100']或者,如果您恰好需要一个列表列表,则在list(..)中包装该项:
>>> [list(b[i:i+4]) for i in range(0, len(b), 4)]
[['1', '0', '1', '0'], ['1', '0', '1', '0'], ['1', '0', '0', '1'], ['0', '1', '0', '0']]此外,如果子列表中的元素必须为int
>>> [list(int(c) for c in b[i:i+4]) for i in range(0, len(b), 4)]
[[1, 0, 1, 0], [1, 0, 1, 0], [1, 0, 0, 1], [0, 1, 0, 0]]发布于 2015-07-04 00:18:30
以下是我的解决方案:
a = 1010101010010100
k = []
m = [int(i) for i in str(a)]
for j in range(0, len(m), 4):
k.append(m[j:j+4])输出:
[[1, 0, 1, 0], [1, 0, 1, 0], [1, 0, 0, 1], [0, 1, 0, 0]]发布于 2015-07-04 00:21:23
你的代码中有很多问题-
我认为你想做的是- b.index(x)%3 == 0而不是b.index(x)!=0%3 (这没有多大意义,除非b.index(x)是0,否则总是假的。
tmp_list.append(x):,这是一个语法错误(你可能应该删除python中的逐位
b.index(x)%3 == 0运算符而不是and运算符&给出元素存在的第一个索引,因为你的字符串只包含1和0,这永远不会超过索引2。相反,您应该考虑使用enumerate函数,该函数将为您提供元素的索引和值。一个建议-
if b.index(x)==0:条件,您可以只在循环外部定义temp_list。if/elif (而不是所有的if)。示例代码:
b = str(a)
list1 = []
tmp_list = []
for i,x in enumerate(b):
if i%4!=0 or i==0:
tmp_list.append(x)
else:
list1.append(tmp_list)
tmp_list=[]
tmp_list.append(x)输出-
[['1', '0', '1', '0'], ['1', '0', '1', '0'], ['1', '0', '0', '1']]https://stackoverflow.com/questions/31210786
复制相似问题