社区所有版块导航
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如何链接2个列表?

ryandanielsim • 3 年前 • 1066 次点击  

我有两张清单

[902920,28393892,93993992,93938939929,929393993928,38982933939393, 883383938393]
[1.9, 1,7, 1,6]

大体上 1.9 链接到 902920,28393892,93993992 1.7 链接到 93938939929,929393993928,38982933939393

在for循环中,我需要 要求得到( 1.9 ,然后是第一个列表中的3个数字) 然后 1.7 接下来的3个数字

要建立这个链接吗?

抱歉,我应该提到1.6可以链接到列表中的下两个数字,而另一个数字1.5可以链接到下一个7。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132767
 
1066 次点击  
文章 [ 1 ]  |  最新文章 3 年前
oda
Reply   •   1 楼
oda    3 年前

more-itertools 有这个吗 grouper 可能对该任务有用的函数。我 replicate it 在这里:

from itertools import zip_longest
def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
    "Collect data into non-overlapping fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
    # grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
    # grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
    args = [iter(iterable)] * n
    if incomplete == 'fill':
        return zip_longest(*args, fillvalue=fillvalue)
    if incomplete == 'strict':
        return zip(*args, strict=True)
    if incomplete == 'ignore':
        return zip(*args)
    else:
        raise ValueError('Expected fill, strict, or ignore')

此功能与 zip ( documentation )以如下所示的方式返回元组的迭代器,其中元组的第一个元素是来自 b 元组的第二个元素是一个由三个元素组成的元组,这些元素取自 a .对于本例,返回的迭代器 拉链 链接 1.9 关于 A. , 1.7 接下来的三个要素 A. 等等

a = [902920,28393892,93993992,93938939929,929393993928,38982933939393, 883383938393]
b = [1.9, 1.7, 1.6]

c = zip(b, grouper(a, 3))

for item in c:
    print(item)

输出

(1.9, (902920, 28393892, 93993992))
(1.7, (93938939929, 929393993928, 38982933939393))
(1.6, (883383938393, None, None))

这个 石斑鱼 函数提供了额外的功能。默认情况下,如果长文档中没有足够的元素 A. 列表要填充一个3元组,空元素将被 None .所以你可以设定 fillvalue 您是否希望获得除以下内容以外的值 没有一个 或者,您甚至可以声明,您不希望像本例中那样使用不完整的元组

c = zip(b, grouper(a, 3, incomplete = 'ignore'))

for item in c:
    print(item)

输出

(1.9, (902920, 28393892, 93993992))
(1.7, (93938939929, 929393993928, 38982933939393))