【问题标题】:Finding length of items from a list从列表中查找项目的长度
【发布时间】:2010-10-10 08:32:52
【问题描述】:

我在 python 中有两个列表

list1=['12aa','2a','c2']

list2=['2ac','c2a','1ac']

首先 - 从 list1 中查找每两项的组合。

第二-从list2中查找每两项的组合。

Third- 从 list1 和 list2 中查找每两项的组合

Fourth- 计算每个组合的总长度

感谢您提供 Python 方面的建议和帮助。

谢谢

【问题讨论】:

  • 您能否解释一下您的示例数据的答案应该是什么以及您是如何得出这个答案的?如果你用一个具体的例子来说明你想要发生的事情,就会更容易理解你的问题。
  • PYTHON中的解决方案”???这听起来有点苛刻。
  • 我只是在做练习,没有做任何功课,抱歉我用词不当,听起来要求很高。我再次编辑了问题并使其准确。谢谢

标签: python arrays


【解决方案1】:
import itertools as it

list1=['12aa','2a','c2']
list2=['2ac','c2a','1ac']

# First- Finding combinations of each two item from list1.
first = list(it.combinations(list1, 2))

# Second- Finding combinations of each two item from list2.
second = list(it.combinations(list2, 2))

# Third- Finding combinations of each two items from list1 and list2
third = list(it.product(list1, list2))

# Fourth- Calculating each combinations total length
for combination in first: # first, second, third
    print combination, len(''.join(combination))

【讨论】:

  • 实际上,我想生成列表中每两个项目的组合以及单个组合中的总字符。其次,我想生成 list1 和 list2 中每两个项目的组合以及单个组合中的总字符数。
  • 非常感谢,现在我遇到了另一个问题。假设从我们的示例 list1 中,我们从三个项目中得到 3 个组合。现在,我想将那个单独的组合传递给一个函数,并且想知道第一项和第二项以进行另一个操作,但又不想弄乱以前的问题
  • 对不起,我不太明白你最后的评论。您能否将原始问题的编辑与示例一起添加?
  • 在不使用组合的情况下还有其他方法吗?因为我发现当我尝试在其他应用程序终端中运行 python 文件时,它无法识别组合()。谢谢
  • 如果您使用的 Python 版本早于 2.6,请在此处查看:docs.python.org/library/itertools.html#itertools.combinations 以获得组合替换功能。
猜你喜欢
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-21
  • 2020-09-24
相关资源
最近更新 更多