編輯:在我試圖舉例說明編碼問題時,我在我想要的結果方面犯了一個錯誤。我已將結果更新為我的實際期望結果。
我有一個名為的串列串列,我希望與一個名為 的姐妹串列(如果這是編碼中的術語)list_of_lists_1并行回圈
,還有一個名為的串列。并且在串列的總數和每個串列中具有相同數量的元素。in 中的每個元素都應與其各自的串列 in回圈,即將與串列和串聯回圈。就像將回圈使用等一樣。 list_of_lists_2person_listlist_of_lists_1list_of_lists_2person_listlist_of_lists_1list_of_lists_2person_a[1, 3, 5][2, 4, 6]persin_b["7", "9", "11"]["8", "10", "12"]
# create lists
list_of_lists_1 = [["1", "3", "5"], ["7", "9", "11"], ["13", "15", "17"]]
list_of_lists_2 = [["2", "4", "6"], ["8", "10", "12"], ["14", "16", "18"]]
person_list = ["person_a", "person_b", "person_c"]
我已經嘗試了以下代碼。然而,輸出僅相當于大約50 pct。的期望結果。
# loop
for i in range(0, len(list_of_lists_1)):
outcome = person_list[i] list_of_lists_1[i][i] list_of_lists_2[i][i]
# some functions and other interesting stuff!
print(outcome)
person_a12
person_b910
person_c1718
# desired outcome (Has been edited)
person_a12
person_a34
person_a56
person_b78
person_b910
person_b1112
person_c1314
person_c1516
person_c1718
我將如何達到預期的結果?
謝謝你。
uj5u.com熱心網友回復:
用于zip()并行回圈串列。
然后,您可以使用嵌套回圈將嵌套串列的元素組合在list_of_lists_X.
鑒于:
list_of_lists_1 = [["1", "3", "5"], ["7", "9", "11"], ["13", "15", "17"]]
list_of_lists_2 = [["2", "4", "6"], ["8", "10", "12"], ["14", "16", "18"]]
person_list = ["person_a", "person_b", "person_c"]
您的結果可以通過以下方式構建:
for suffixes_1, suffixes_2, name in zip(list_of_lists_1, list_of_lists_2, person_list):
for s1, s2 in zip(suffixes_1, suffixes_2):
outcome = name s1 s2
print(outcome)
uj5u.com熱心網友回復:
@Barmar 的解決方案更加簡潔,但無論如何我都會發布。
list_of_lists_1 = [["1", "3", "5"], ["7", "9", "11"], ["13", "15", "17"]]
list_of_lists_2 = [["2", "4", "6"], ["8", "10", "12"], ["14", "16", "18"]]
person_list = ["person_a", "person_b", "person_c"]
for n,p in enumerate(person_list):
output = p
for digits in zip(list_of_lists_1[n],list_of_lists_2[n]):
output = digits[0] digits[1]
print(output)
uj5u.com熱心網友回復:
通過擴展@Barmar 的答案(https://stackoverflow.com/a/71243300/218663),您可以通過串列理解來做到這一點:
list_of_lists_1 = [["1", "3", "5"], ["7", "9", "11"], ["13", "15", "17"]]
list_of_lists_2 = [["2", "4", "6"], ["8", "10", "12"], ["14", "16", "18"]]
person_list = ["person_a", "person_b", "person_c"]
result = (
f"{name}{s1}{s2}"
for suffixes_1, suffixes_2, name in zip(list_of_lists_1, list_of_lists_2, person_list)
for s1, s2 in zip(suffixes_1, suffixes_2)
)
for outcome in result:
print(outcome)
給你:
person_a12
person_a34
person_a56
person_b78
person_b910
person_b1112
person_c1314
person_c1516
person_c1718
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/433020.html
