簡體   English   中英

在 Python 列表中查找並組合以特定字母開頭的元素

[英]Find and combine elements starting with specific letters in Python Lists

我有一個單詞列表:假設

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

另一個:

aList = ['t','s']

我想在myList中找到以aList中的元素開頭的元素並將它們組合起來。

喜歡:

> typical system
> tower source

我可以使用listItem.startswith找到元素,但我無法根據它們的放置順序使用aList來組合它們。

我怎樣才能做到這一點?

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)

Output:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM