我有一个列表列表:
ex = [['1001'],['0010'],['1101'],['0000']]
我想将此列表列表拆分为较小的列表。我还有另一个列表,其中包含要分割的索引:
track = [1,3]
所以我想分割这个列表列表,以得到以下结果:
sublist = [
[[1,0],[0,0],[1,1],[0,0]],
[[0,1],[1,0],[0,1],[0,0]]
]
我已经尝试了一个简单的列表:
ex = [1,0,0,1]
start = 0
position = []
for i in track:
position.append(ex[start:i+1])
start = i+1
但是在这种情况下,我的列表已经有整数,而原始列表有字符串。
如何在具有字符串而不是整数的列表列表上实现此目的?我不知道从哪里开始?
答案 0 :(得分:1)
您似乎想将数字拆分为数字,然后将每个数字的前两位和后两位放入结果的单独列表中-您可以进行以下操作:
# what you got
ex = [['1001'],['0010'],['1101'],['0000']]
# what you want
sublist = [[[1,0],[0,0],[1,1],[0,0]],
[[0,1],[1,0],[0,1],[0,0]]]
# how to get there: create single integers from each string
# list comprehension, see below for answers about them
digits = [ list(map(int,l)) for inner in ex for l in inner]
print(digits )
# create the results
result = [ [],[] ]
for inner in digits:
result[ 0].append( inner[:2] ) # list slicing, see below for answers about it
result[-1].append( inner[2:] )
print(result)
输出(重新格式化):
# split into digits
[[1, 0, 0, 1], [0, 0, 1, 0], [1, 1, 0, 1], [0, 0, 0, 0]]
# put into results
[[[1, 0], [0, 0], [1, 1], [0, 0]],
[[0, 1], [1, 0], [0, 1], [0, 0]]]
Built in functions可帮助您解释map()和其他有用的功能。读起来也很有趣:
答案 1 :(得分:0)
sublist
是最终列表。 subsublist
被视为中间临时列表。track
是外部循环ex
是内循环ex = [['1001'],['0010'],['1101'],['0000']]
track = [1,3]
subsublist = []
sublist = []
start=0
for index in track:
# print(index)
if start == 0:
end=index+1
else:
end=None
for item in ex:
subsublist.append([item[0][start:end]])
sublist.append(subsublist)
start=end
subsublist = []
print(sublist)
[UPDATE]另一种使代码通用的尝试!
ex = [['100190'],['001099'],['110187'],['000050']]
tracks = [1,3,6]
subsublist = []
sublist = []
start=0
for track in tracks:
indexOfTrack = tracks.index(track)
if indexOfTrack == 0:
end=track+1
elif indexOfTrack > 0 and indexOfTrack < len(tracks)-1:
end = track+1
else:
end=None
for item in ex:
subsublist.append([item[0][start:end]])
sublist.append(subsublist)
start=end
subsublist = []
print(sublist)
答案 2 :(得分:0)
import itertools
import sys
ex = [['1001'], ['0010'], ['1101'], ['0000']]
track = [1, 3]
# [a,b)
it = itertools.chain(map(lambda x: x - 1, track), [sys.maxsize])
last = next(it, None)
result = []
for curr in it:
temp = []
for s in itertools.chain.from_iterable(ex):
temp.append(list(map(int, s[last:curr])))
result.append(temp)
last = curr
print(result)