【问题标题】:split each item in list拆分列表中的每个项目
【发布时间】:2014-03-21 09:24:32
【问题描述】:

是否可以拆分列表中的项目并即时生成新列表? 基本上我得到了一个 ushort 的列表并想要生成一个 ubytes 的列表:

input = [1036, 1055, 26, 29787, 9, 4206, 41, 7, 1036, 8302, 130, 4, 268, 4206]
out = [4, 12, 4, 31, 0, 26, 116, 91, 0, 9, 16, 110, 0, 41, 0, 7, 4, 12, 32, 110, 0, 130, 0, 4, 1, 12, 16, 110]

我可以很容易地生成一个元组列表,但是我怎样才能删除这些元组并将它们合并到一个大列表中呢?

out_temp = [(x>>8, x&0xFF) for x in input]

【问题讨论】:

  • 为什么不使用 lambda 函数?

标签: python list


【解决方案1】:

您可以这样使用列表推导:

>>> in_ = [1036, 1055, 26, 29787, 9, 4206, 41, 7, 1036, 8302, 130, 4, 268, 4206]
>>> [y for x in in_ for y in (x >> 8, x & 0xff)]
[4, 12, 4, 31, 0, 26, 116, 91, 0, 9, 16, 110, 0, 41, 0, 7, 4, 12, 32, 110, 0, 130, 0, 4, 1, 12, 16, 110]

或使用itertools.chain.from_iterable:

>>> import itertools
>>> list(itertools.chain.from_iterable((x >> 8, x & 0xff) for x in in_))
[4, 12, 4, 31, 0, 26, 116, 91, 0, 9, 16, 110, 0, 41, 0, 7, 4, 12, 32, 110, 0, 130, 0, 4, 1, 12, 16, 110]

顺便说一句,不要使用input 作为变量名。它隐藏了内置函数input

【讨论】:

    【解决方案2】:

    根据您想对转换后的数据做什么,您可能还对array.array 感兴趣。

    >>> a = array.array("H", input)
    >>> a.byteswap()
    >>> a.tostring()
    '\x04\x0c\x04\x1f\x00\x1at[\x00\t\x10n\x00)\x00\x07\x04\x0c n\x00\x82\x00\x04\x01\x0c\x10n'
    >>> list(bytearray(a.tostring()))
    [4, 12, 4, 31, 0, 26, 116, 91, 0, 9, 16, 110, 0, 41, 0, 7, 4, 12, 32, 110, 0, 130, 0, 4, 1, 12, 16, 110]
    

    【讨论】:

    • byteswap 应该有条件地完成。 (取决于sys.byteorder
    • falsetru:这真的取决于 OP 想要做什么。
    • 我的意思是答案中的代码在大端系统中不会产生相同的输出。您添加了byteswap 以使结果与问题中的out 匹配。不是吗?
    • @falsetru:是的,我当然做了,但他的代码主要是为了演示这个概念。根据实际用例,可能需要有条件地进行字节交换(尽管大端系统现在大部分——而且理所当然地——死了)。
    【解决方案3】:

    正如SO question 中指出的,您还可以使用generator 函数:

    input_data = [1036, 1055, 26, 29787, 9, 4206, 41, 7, 1036, 8302, 130, 4, 268, 4206]
    
    def convert(x):
        for i in x:
            yield i>>8
            yield i&0xFF
    
    print list(convert(input_data))
    

    结果

    [4, 12, 4, 31, 0, 26, 116, 91, 0, 9, 16, 110, 0, 41, 0, 7, 4, 12, 32, 110, 0, 130, 0, 4, 1, 12, 16, 110]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-02
      • 2012-09-30
      • 1970-01-01
      • 2014-04-05
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多