如何从另一个列表创建和更新相同的列表
How to create and update the same list from another list
我有两个列表:
a= ['a','b','c','d','e','f','4','to','the','words']
b = [[1,2,3],[1,2,3,4,5],[1,2]]
现在我需要另一个更新值的列表,例如:
c = ['a','b','c'] w.r.t list of list in b
c = ['d','e','f','4','to'] #update new list by removing previous one
c = ['the','words']
and so on......
如何更新上述列表?
你的问题不是很清楚,但你似乎在寻找这样的东西:
您可以保留索引的偏移量,以便根据提供的索引向新列表中添加元素。
a = ['a','b','c','d','e','f','4','to','the','words']
b = [[1,2,3],[1,2,3,4,5],[1,2]]
last_offset = 0
cs = []
for bi in b:
cs.append([a[bii + last_offset - 1] for bii in bi])
last_offset += max(bi)
print(cs)
试试这个:
a= ['a','b','c','d','e','f','4','to','the','words']
b = [[1,2,3],[1,2,3,4,5],[1,2]]
c= []
start = 0
for ele in b:
end = len(ele) + start
c.append(a[start:end])
start = end
print(c)
也许这会有帮助?
a= ['a','b','c','d','e','f','4','to','the','words']
b = [[1,2,3],[1,2,3,4,5],[1,2]]
itr_list = iter(a)
for mini_list in b:
try:
res = [next(itr_list) for _ in mini_list]
except StopIteration:
print(res)
break
print(res)
此代码采用 a
并使其成为迭代器,因此您可以使用 next 命令从中请求下一个值。如果您对 b
中的值和 a
.
的长度有疑问,这将有所帮助
然而,b
似乎是多余的,您可以只给出一个整数,其中包含要从 a
获得的值的数量。
如果这是你的意图,那么你可以使用这样的东西:
a= ['a','b','c','d','e','f','4','to','the','words']
b = [3,5,2]
i=0
for val in b:
print(a[i:val+i])
i=val
可能需要的另一个功能是您可能需要来自 a
的并行值。为此,您必须使用 b
:
中的列表
a= ['a','b','c','d','e','f','4','to','the','words']
b = [[1,2,3],[1,2,4,5],[6,7,1]]
for mini_list in b:
print([a[val-1] for val in mini_list])
此代码使用 b
的值作为 a
中的索引。你应该注意到我减少了 1 因为 zero-base numbering.
我有两个列表:
a= ['a','b','c','d','e','f','4','to','the','words']
b = [[1,2,3],[1,2,3,4,5],[1,2]]
现在我需要另一个更新值的列表,例如:
c = ['a','b','c'] w.r.t list of list in b
c = ['d','e','f','4','to'] #update new list by removing previous one
c = ['the','words']
and so on......
如何更新上述列表?
你的问题不是很清楚,但你似乎在寻找这样的东西:
您可以保留索引的偏移量,以便根据提供的索引向新列表中添加元素。
a = ['a','b','c','d','e','f','4','to','the','words']
b = [[1,2,3],[1,2,3,4,5],[1,2]]
last_offset = 0
cs = []
for bi in b:
cs.append([a[bii + last_offset - 1] for bii in bi])
last_offset += max(bi)
print(cs)
试试这个:
a= ['a','b','c','d','e','f','4','to','the','words']
b = [[1,2,3],[1,2,3,4,5],[1,2]]
c= []
start = 0
for ele in b:
end = len(ele) + start
c.append(a[start:end])
start = end
print(c)
也许这会有帮助?
a= ['a','b','c','d','e','f','4','to','the','words']
b = [[1,2,3],[1,2,3,4,5],[1,2]]
itr_list = iter(a)
for mini_list in b:
try:
res = [next(itr_list) for _ in mini_list]
except StopIteration:
print(res)
break
print(res)
此代码采用 a
并使其成为迭代器,因此您可以使用 next 命令从中请求下一个值。如果您对 b
中的值和 a
.
然而,b
似乎是多余的,您可以只给出一个整数,其中包含要从 a
获得的值的数量。
如果这是你的意图,那么你可以使用这样的东西:
a= ['a','b','c','d','e','f','4','to','the','words']
b = [3,5,2]
i=0
for val in b:
print(a[i:val+i])
i=val
可能需要的另一个功能是您可能需要来自 a
的并行值。为此,您必须使用 b
:
a= ['a','b','c','d','e','f','4','to','the','words']
b = [[1,2,3],[1,2,4,5],[6,7,1]]
for mini_list in b:
print([a[val-1] for val in mini_list])
此代码使用 b
的值作为 a
中的索引。你应该注意到我减少了 1 因为 zero-base numbering.