社区所有版块导航
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将列表中的元素以偶发模式提取到元组中

QJ123123 • 3 年前 • 1568 次点击  

我有一个列表,它有这样的模式[浮动,字符串,浮动字符串…]但在模式中,它偶尔会变成[float,string,float,string,string,float string…]。我想做的是将列表中的元素以(float、name、NONETYPE或STRING)的格式提取到元组中,以便以后对其进行处理。下面是一个小例子:

arr = [1150.1, 'James', 3323.1, 'Steve', 9323.1, 'John', 1233.1, 'Gary', 'criminal', 3293.1, 'Josh', 9232.1, 'Daniel', 'criminal']

我想提取列表,使元组如下所示:

(1150.1, James, NONE)

(3323.1, Steve, NONE)

(9323.1, John, NONE)

(1233.1, Gary, criminal)

(3293.1, Josh, NONE)

(9232.1, Daniel, criminal)

到目前为止,我已经尝试在数组中检查该类型的下一个索引,但它不起作用:

for index in range(len(arr)):
    if type(arr[index]) == float and type(arr[index+1]) == str:
        tup = arr[index], arr[index+1], None
        print(tup)
    elif type(arr[index]) == float and type(arr[index+1]) == str and type(arr[index+2]) == str:
        tup = arr[index], arr[index + 1], arr[index+2]
        print(tup)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133419
 
1568 次点击  
文章 [ 4 ]  |  最新文章 3 年前
Sash Sinha
Reply   •   1 楼
Sash Sinha    3 年前

也许你可以使用while循环:

from typing import Optional, NamedTuple


class Element(NamedTuple):
    value: float
    name: str
    profession: Optional[str] = None


def main() -> None:
    arr = [
        1150.1, 'James',
        3323.1, 'Steve',
        9323.1, 'John',
        1233.1, 'Gary', 'criminal',
        3293.1, 'Josh',
        9232.1, 'Daniel', 'criminal',
    ]
    parsed_elements = []
    i = 0
    while i <= len(arr) - 2:
        if isinstance(arr[i + 2], str):
            parsed_elements.append(Element(*arr[i:i + 3]))
            i += 3
        else:
            parsed_elements.append(Element(*arr[i:i + 2]))
            i += 2
    print('\n'.join(str(e) for e in parsed_elements))


if __name__ == '__main__':
    main()

输出:

Element(value=1150.1, name='James', profession=None)
Element(value=3323.1, name='Steve', profession=None)
Element(value=9323.1, name='John', profession=None)
Element(value=1233.1, name='Gary', profession='criminal')
Element(value=3293.1, name='Josh', profession=None)
Element(value=9232.1, name='Daniel', profession='criminal')
Andrej Kesely
Reply   •   2 楼
Andrej Kesely    3 年前

另一个解决方案:

from itertools import groupby

g1 = (g for v, g in groupby(arr, type) if v is float)
g2 = (g for v, g in groupby(arr, type) if v is str)

out = [(next(a), *[*b, None][:2]) for a, b in zip(g1, g2)]
print(out)

印刷品:

[
    (1150.1, "James", None),
    (3323.1, "Steve", None),
    (9323.1, "John", None),
    (1233.1, "Gary", "criminal"),
    (3293.1, "Josh", None),
    (9232.1, "Daniel", "criminal"),
]
not_speshal
Reply   •   3 楼
not_speshal    3 年前

您可以检查“float”、“string”模式,并相应地追加:

output = list()
for i, element in enumerate(arr):
    if isinstance(element, float) and isinstance(arr[i+1], str):
        if isinstance(arr[i+2], str):
            t = tuple(arr[i:i+3])
        else:
            t = tuple(arr[i:i+2]+["NONE"])
        output.append(t)

>>> output
[(1150.1, 'James', 'NONE'),
 (3323.1, 'Steve', 'NONE'),
 (9323.1, 'John', 'NONE'),
 (1233.1, 'Gary', 'criminal'),
 (3293.1, 'Josh', 'NONE'),
 (9232.1, 'Daniel', 'criminal')]
BrokenBenchmark
Reply   •   4 楼
BrokenBenchmark    3 年前

可以使用辅助列表跟踪自上次浮点值以来看到的数组元素。每当看到浮点时,将现有元素转换为元组并清除辅助列表:

result = []
items = []

for item in arr:
    if isinstance(item, float) and items:
        if len(items) < 3:
            items.append(None)
        result.append(tuple(items))
        items = [item]
    else:
        items.append(item)
    
result.append(tuple(items))

print(result)

这将产生:

[
 (1150.1, 'James', None), (3323.1, 'Steve', None),
 (9323.1, 'John', None), (1233.1, 'Gary', 'criminal'),
 (3293.1, 'Josh', None), (9232.1, 'Daniel', 'criminal')
]