社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

基于python中的条件创建一个列表以创建一个唯一的列表

lookinsideu • 5 年前 • 1624 次点击  

我有两个清单:

a= [0,0,0,1,1,1,3,3,3]
b= ['a','b','c','d','e','f','g','h','i']
output = [['a','b','c'],['d','e','f'],['g','h','i']]

A和B是相同长度的列表。 我需要一个输出数组,当list-a中的值从0更改为1或从1更改为3时,应该在输出列表中创建一个新列表。 有人能帮忙吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40227
 
1624 次点击  
文章 [ 4 ]  |  最新文章 5 年前
Mauro Baraldi
Reply   •   1 楼
Mauro Baraldi    6 年前

添加标记时 算法 ,我相信你想要一个没有那么多魔法的解决方案。

>>> def merge_lists(A, B):
...     output = []
...     sub_list = []
...     current = A[0]
...     for i in range(len(A)):
...         if A[i] == current:
...             sub_list.append(B[i])
...         else:
...             output.append(sub_list)
...             sub_list = []
...             sub_list.append(B[i])
...             current = A[i]
...     output.append(sub_list)
...     return output
... 
>>> a= [0,0,0,1,1,1,3,3,3]
>>> b= ['a','b','c','d','e','f','g','h','i']
>>> merge_list(a, b)
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
Thierry Lathuille
Reply   •   2 楼
Thierry Lathuille    6 年前

使用 groupby ,您可以:

from itertools import groupby

a= [0,0,0,1,1,1,3,3,3]
b= ['a','b','c','d','e','f','g','h','i']

iter_b = iter(b)
output = [[next(iter_b) for _ in group] for key, group in groupby(a)]

print(output)
# [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

子句 产生具有相同值的连续组 a . 对于每个组,我们创建一个列表,其中包含 b 因为组中有值。

Rocky Li
Reply   •   3 楼
Rocky Li    6 年前

不使用任何通过使用字典的导入的更简单的方法:

a= [0,0,0,1,1,1,3,3,3]
b= ['a','b','c','d','e','f','g','h','i']

d = {e: [] for e in set(a)} # Create a dictionary for each of a's unique key
[d[e].append(b[i]) for i, e in enumerate(a)] # put stuff into lists by index
lofl = list(d.values())

>>> lofl
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
Daniel Mesejo
Reply   •   4 楼
Daniel Mesejo    6 年前

使用 groupby :

from itertools import groupby
from operator import itemgetter

a = [0, 0, 0, 1, 1, 1, 3, 3, 3]
b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

output = [list(map(itemgetter(1), group)) for _, group in groupby(zip(a, b), key=itemgetter(0))]
print(output)

产量

[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]