在Python列表中查找并组合以特定字母开头的元素
我有一个单词列表: 假设 还有一个:在Python列表中查找并组合以特定字母开头的元素,python,python-3.x,list,arraylist,Python,Python 3.x,List,Arraylist,我有一个单词列表: 假设 还有一个: aList = ['t','s'] 我想在myList中找到以aList中的元素开头的元素,并将它们组合起来 比如: 我可以找到listItem.startswith中的元素,但无法根据它们的放置顺序使用列表将它们组合起来 我该怎么做 from itertools import product # The data. words = ['typical', 'tower', 'temporary', 'system', 'source', 'sky']
aList = ['t','s']
我想在myList中找到以aList中的元素开头的元素,并将它们组合起来
比如:
我可以找到listItem.startswith中的元素,但无法根据它们的放置顺序使用列表将它们组合起来
我该怎么做
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')
你想要所有可能的组合吗?@AnnZen不是所有的组合,因为它会冻结终端。这些答案之一解决了你的问题吗?如果没有,你能提供更多的信息来帮助回答这个问题吗?否则,请考虑把答案最好的答案标在上下投票箭头上。请参阅并感谢您的回答,但是列表很大,大约有2000多个条目,如果我尝试使用您共享的方法,它会冻结系统,并终止终端返回。@HarisIjazWarraich好的,在这种情况下,不要生成所有可能的短语跳过笛卡尔积步骤。相反,只需从单词组中随机选择所需数量的短语即可。
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')