代码之家  ›  专栏  ›  技术社区  ›  Shashi Shankar Singh

使用python将查询结果转换为列表

  •  -2
  • Shashi Shankar Singh  · 技术社区  · 7 年前

    我有一个查询,给出如下结果。

    abc=[(1531,), (4325,), (9204,)]
    

    如何将其转换为以下列表?

    def=['1531','4325','9204']
    

    我将始终使用整数而不是字符串作为结果。

    5 回复  |  直到 7 年前
        1
  •  1
  •   zhangslob    7 年前

    我不明白,循环很简单。为什么要用别人的复杂?

    abc = [(1531,), (4325,), (9204,)]
    def_ = []
    
    for i in abc:
        def_.append(str(i[0]))
    
    print(def_)
    
        2
  •  1
  •   Rakesh    7 年前
    import itertools
    abc=[(1531,), (4325,), (9204,)]
    print( list(map(str, itertools.chain.from_iterable(abc))) )
    

    输出:

    ['1531', '4325', '9204']
    
    • itertools.chain.from_iterable 平展列表
    • map 将列表中的所有元素转换为str
        3
  •  0
  •   blhsing    7 年前

    使用迭代器:

    from operator import itemgetter
    print(list(map(itemgetter(0), abc)))
    

    列表理解:

    print([i[0] for i in abc])
    

    两种输出:

    [1531, 4325, 9204]
    
        4
  •  0
  •   Sushant    7 年前

    使用 itertools -

    import itertools
    abc = list(itertools.chain.from_iterable(abc))
    

    使用列表理解-

    [i for x in abc for i in x]
    
        5
  •  0
  •   Sunitha    7 年前

    用正常的列表理解

    >>> abc = [(1531,), (4325,), (9204,)]
    >>> dfg = [val for items in abc for val in items]
    >>> dfg
    [1531, 4325, 9204]
    

    如果查询结果太大,请考虑使用 itertools.chain

    >>> from itertools import chain
    >>> list(chain(*abc))
    [1531, 4325, 9204]