![](/img/trans.png)
[英]How to traverse a Python List and its List elements , splitting strings within each element and writing out a new list
[英]Concatenate each element of a list with all the elements of its list and put these strings inside a new list
#Load the input lists
load_names_list = ['Katherine', 'María Jose', 'Steve']
load_surnames_list = ['Taylor', 'Johnson', 'White', 'Clark']
#Shuffle the data lists: ['element_AA element_AA' , 'element_AA element_AB' , ... ]
names_with_names_list = []
surnames_with_surnames_list = []
names_with_surnames_list = []
print(names_with_names_list)
print(surnames_with_surnames_list)
print(names_with_surnames_list)
names_with_names_list
將每個名稱與列表load_names_list
中的每個名稱進行匹配,例如: name_A name_A
、 name_A name_B
,始終在兩者之間留一個空格
surnames_with_surnames_list
它與處理列表names_with_names_list
的元素的過程相同,但使用列表load_surnames_list
names_with_surnames_list
這種情況有些不同,因為您必須測試 2 個列表( load_names_list
和load_surnames_list
)的元素之間的所有可能順序
給我最多問題的連接是獲取列表names_with_surnames_list
所需的連接
這將是打印這 3 個字符串列表中的每一個時應返回的 output。
#for names_with_names_list
['Katherine Katherine', 'Katherine María Jose', 'Katherine Steve', 'María Jose Katherine', 'María Jose María Jose', 'María Jose Steve', 'Steve Katherine', 'Steve María Jose', 'Steve Steve']
#for surnames_with_surnames_list
['Taylor Taylor', 'Taylor Johnson', 'Taylor White', 'Taylor Clark', 'Johnson Taylor', 'Johnson Johnson', 'Johnson White', 'Johnson Clark', 'White Taylor', 'White Johnson', 'White White', 'White Clark', 'Clark Taylor', 'Clark Johnson', 'Clark White', 'Clark Clark']
#for names_with_surnames_list
['Katherine Taylor', 'Katherine Johnson', 'Katherine White', 'Katherine Clark', 'María Jose Taylor', 'María Jose Johnson', 'María Jose White', 'María Jose Clark', 'Steve Taylor', 'Steve Johnson', 'Steve White', 'Steve Clark', 'Taylor Katherine', 'Taylor María Jose', 'Taylor Steve', 'Johnson Katherine', 'Johnson María Jose', 'Johnson Steve', 'White Katherine', 'White María Jose', 'White Steve', 'Clark Katherine', 'Clark María Jose', 'Clark Steve']
我應該怎么做才能從 2 個輸入列表中獲取這 3 個列表? (注意元素之間總是有一個空格)
您可以使用itertools.product
(對於具有兩個不同列表的情況也可以chain
):
from itertools import product, chain
load_names_list = ['Katherine', 'María Jose', 'Steve']
load_surnames_list = ['Taylor', 'Johnson', 'White', 'Clark']
names_with_names_list = [f"{a} {b}" for a,b in product(load_names_list, repeat=2)]
surnames_with_surnames_list = [f"{a} {b}" for a,b in chain(product(load_names_list, load_surnames_list),
product(load_surnames_list, load_names_list))]
names_with_surnames_list = [f"{a} {b}" for a,b in product(load_surnames_list, repeat=2)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.