【问题标题】:python list from both strings and for loop来自字符串和for循环的python列表
【发布时间】:2012-07-23 14:03:52
【问题描述】:

有没有一种方法可以同时使用字符串和生成器(for 循环)来创建列表。

list() 只接受一个参数。到目前为止我能看到的唯一方法是:

row = ['string1','string2']+list((t.string3[-7:]) for t in tobject)

我错过了什么?

【问题讨论】:

  • 嗯,我的意思是......你希望它看起来像什么?与现在相比,您希望获得什么?

标签: python list for-loop


【解决方案1】:

您只需要在一行中完成吗? chain() 有效,但对我来说看起来如此难以理解。以下可能不太优雅,但我认为它更具可读性:

row = ['string1', 'string2']
row.extend(t.string3[-7:] for t in tobject)

【讨论】:

  • 其实,在这个特别的案例中,我觉得这比chain更优雅。
  • 是什么让它不那么优雅?有时 2 行比 1 更好。(+1 来自我)
【解决方案2】:
import itertools
list(itertools.chain(('string1','string2'), (t.string3[-7:] for t in tobject)))

【讨论】:

    【解决方案3】:

    不,您必须连接两个列表。

    您可能更喜欢 chain 迭代,然后对它们调用一次 list

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-30
      • 2023-01-24
      • 2021-03-22
      • 1970-01-01
      • 2023-02-26
      • 1970-01-01
      • 2020-06-21
      • 2021-08-25
      相关资源
      最近更新 更多