簡體   English   中英

將列表的每個元素與其列表的所有元素連接起來,並將這些字符串放入一個新列表中

[英]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_Aname_A name_B ,始終在兩者之間留一個空格

  • surnames_with_surnames_list它與處理列表names_with_names_list的元素的過程相同,但使用列表load_surnames_list

  • names_with_surnames_list這種情況有些不同,因為您必須測試 2 個列表( load_names_listload_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.

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