【问题标题】:Find and combine elements starting with specific letters in Python Lists在 Python 列表中查找并组合以特定字母开头的元素
【发布时间】:2020-10-05 12:26:06
【问题描述】:

我有一个单词列表: 假设

myList =['typical', 'tower', 'temporary', 'system','source','sky']

还有一个:

aList = ['t','s']

我想在 myList 中找到以 aList 中的元素开头的元素并将它们组合起来。

喜欢:

> typical system
> tower source

我能够找到带有listItem.startswith 的元素,但我无法根据它们的放置顺序使用 aList 来组合它们。

我该怎么做?

【问题讨论】:

标签: python python-3.x list arraylist


【解决方案1】:
from itertools import product

# The data.
words = ['typical', 'tower', 'temporary', 'system', 'source', 'sky']
letters = ['t', 's']

# Organize the words by starting letter.
word_groups = [
    [w for w in words if w.startswith(let)]
    for let in letters
]

# A Cartesian product of all word groups gives every possible phrase.
phrases = list(product(*word_groups))

# Check.
for p in phrases:
    print(p)

输出:

('typical', 'system')
('typical', 'source')
('typical', 'sky')
('tower', 'system')
('tower', 'source')
('tower', 'sky')
('temporary', 'system')
('temporary', 'source')
('temporary', 'sky')

【讨论】:

  • 感谢您的回答,但是列表很大,大约有2000多个项目,如果我尝试使用您共享的方法,它会冻结系统,并且终端返回“killed”。跨度>
  • @HarisIjazWarraich 好的,在这种情况下,不要生成所有可能的短语(跳过笛卡尔积步骤)。取而代之的是从word_groups 中随机选择所需数量的短语。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-20
  • 1970-01-01
  • 2022-06-22
  • 2017-04-13
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
相关资源
最近更新 更多