Python zip只包含

2024-09-28 01:23:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个将数据从一种类型转换为另一种类型的脚本。 源文件可以有一个、两个或全部:位置、旋转和缩放数据。你知道吗

在对输出文件进行转换之后,我的脚本会将3个压缩到一起。你知道吗

在这种情况下,我的源文件只包含位置数据。 所以最后返回的列表是:

pData = [['-300.2', '600.5'],['150.12', '280.7'],['19.19', '286.56']]
rData = []
sData = []

translationData = list(zip(pData, rData, sData))

如果我尝试这样做,它将返回[],因为最短的列表是[]。 如果我尝试:

translationData = list(zip_longest(pData, rData, sData))

我得到:

`[(['-300.2', '600.5'], None, None), (['150.12', '280.7'], None, None), (['19.19', '286.56'], None, None)]`

有没有办法只压缩包含数据的列表,或者从列表中的元组中删除None?你知道吗

提前谢谢!你知道吗


Tags: 文件数据脚本none类型列表longest情况
3条回答

您可以修改zip_longest的纯Python版本(给定documentation),并创建一个版本来执行您想要的操作:

from itertools import chain, repeat

class ZipExhausted(Exception):
    pass

def zip_longest(*args, **kwds):
    # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
    fillvalue = kwds.get('fillvalue')
    counter = len(args) - 1
    def sentinel():
        nonlocal counter
        if not counter:
            raise ZipExhausted
        counter -= 1
        yield fillvalue
    fillers = repeat(fillvalue)
    iterators = [chain(it, sentinel(), fillers) for it in args]
    try:
        while iterators:
            res = []
            for it in iterators:
                value = next(it)
                if value != fillvalue:
                    res.append(value)
            yield tuple(res)
    except ZipExhausted:
        pass

pData = [['-300.2', '600.5'],['150.12', '280.7'],['19.19', '286.56']]
rData = []
sData = []

translationData = list(zip_longest(pData, rData, sData))
print(translationData)

输出:

[(['-300.2', '600.5'],), (['150.12', '280.7'],), (['19.19', '286.56'],)]

如果出于某种原因不想导入或使用列表理解等:

  1. 对要压缩的列表进行分组(allLists)
  2. 然后循环分组以检查每个分组中是否有任何内容
  3. 将包含数据的组附加在一起(可压缩)
  4. 最后,*传递过滤分组的zip(*zippable)

    alist = ['hoop','joop','goop','loop']
    blist = ['homp','jomp','gomp','lomp']
    clist = []
    dlist = []
    
    allLists = [alist,blist,clist,dlist]
    
    zippable = []
    
    for fullList in allLists:
        if fullList:
            zippable.append(fullList)
    
    finalList = list(zip(*zippable))
    
    print(finalList)
    

只是另一个可能的解决方案

您可以使用嵌入在list comp中的^{}内置项。你知道吗

Note: In Python 3 filter returns an iterator, so you will need to call tuple() on it. (unlike in py2)

pData = [['-300.2', '600.5'],['150.12', '280.7'],['19.19', '286.56']]
rData = []
sData = []

from itertools import zip_longest  # izip_longest for python 2
[tuple(filter(None, col)) for col in zip_longest(pData, rData, sData)]

结果:

[(['-300.2', '600.5'],), (['150.12', '280.7'],), (['19.19', '286.56'],)]

相关问题 更多 >

    热门问题