【问题标题】:How to print out the first character of each list, then print the next character如何打印出每个列表的第一个字符,然后打印下一个字符
【发布时间】:2013-10-20 06:15:34
【问题描述】:

假设我有一个列表:

x = ['abc', 'd', 'efgh']

我正在尝试创建一个函数,以便返回所需的输出:

a d e b f c g h

这实质上是获取每个元素的第一个字符,然后如果该区域没有索引,则跳到下一个元素。

有没有使用 itertools 或 zip 函数的替代方法?

我试过了:

for i in x:
      print(i[0], i[1], i[2]....etc)

但这只会给我一个错误,因为列表的第二个元素超出了范围。

谢谢!

【问题讨论】:

    标签: python list generator alternate


    【解决方案1】:

    当然...仔细看看并尝试了解这里发生了什么...

    out = []
    biggest = max(len(item) for item in x)
    for i in range(biggest):
        for item in x:
            if len(item) > i:
                out.append(item[i])
    

    而不是out,我会考虑yield 在生成器中返回项目。

    【讨论】:

      【解决方案2】:

      使用来自 itertools 的 roundrobin recipe

      def roundrobin(*iterables):
          "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
          # Recipe credited to George Sakkis
          pending = len(iterables)
          nexts = cycle(iter(it).next for it in iterables)
          while pending:
              try:
                  for next in nexts:
                      yield next()
              except StopIteration:
                  pending -= 1
                  nexts = cycle(islice(nexts, pending))
      

      演示:

      >>> x = ['abc', 'd', 'efgh']
      >>> from itertools import cycle, islice
      >>> list(roundrobin(*x))
      ['a', 'd', 'e', 'b', 'f', 'c', 'g', 'h']
      

      另一种选择是使用itertools.izip_longestitertools.chain.from_iterable

      >>> from itertools import izip_longest, chain
      >>> x = ['abc', 'd', 'efgh']
      >>> sentinel = object()
      >>> [y for y in chain.from_iterable(izip_longest(*x, fillvalue=sentinel)) 
                                                                 if y is not sentinel]
      ['a', 'd', 'e', 'b', 'f', 'c', 'g', 'h']
      

      【讨论】:

      • 我会选择y is not sentinel ...以防万一y有一个时髦的定义__ne__。 (当然,串串没关系,但是进去是个好习惯)。
      • @mgilson 感谢您清除它,实际上在我的真实代码中使用了is not,但在这里我选择了!=,因为我对此有点怀疑。 ;-)
      • 考虑你的听众:)
      • @beroe 是的,我知道,我完全错过了问题中的 w/o using itertools 或 zip 函数? 行。 ://
      猜你喜欢
      • 2021-02-24
      • 1970-01-01
      • 2013-02-23
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 2019-03-19
      相关资源
      最近更新 更多