問題是合并兩個串列索引,例如:
a = [ab,bc,cd]
b = []
預期輸出:
ans = [ab,bc,cd]
我試過這個
a = input("enter the list 1:")
list1 = a.split(",")
b = input("enter the list 2:")
list2 = b.split(",")
if list2 == EMPTY_LIST:
print(list1)
else:
res = [i j for i, j in zip(list1,list2)]
print("Ans: ",res)
但輸出是
enter the list 1:abi,ajith
enter the list 2:
Ans: ['abi']
我需要的預期輸出
enter the list 1:abi,ajith
enter the list 2:
Ans: ['abi','ajith']
uj5u.com熱心網友回復:
請嘗試以下方法:
a = input("enter the list 1:")
list1 = a.split(",")
b = input("enter the list 2:")
list2 = b.split(",")
if not list2:
print(list1)
else:
res = [_ for _ in (list1 list2) if len(_)]
print("Ans: ",res)
uj5u.com熱心網友回復:
您可能還應該處理list2不為空但沒有相同數量的元素的情況list1
如果您用空字串填充串列,則可以毫無問題地壓縮它們
list1 = ["ab","bc","cd"]
list2 = []
n=max(len(list1),len(list2))
for i in range(n):
if i >= len(list1): a.append("")
if i >= len(list2): b.append("")
res = [i j for i, j in zip(list1,list2)]
或者更簡單的方法:
import itertools as it
list1 = ["ab","bc","cd"]
list2 = []
[i j for i, j in it.zip_longest(list1, list2, fillvalue="")]
uj5u.com熱心網友回復:
這里有幾個問題。首先,輸入總是回傳一個字串。如果您在回傳之前沒有輸入任何內容,它將是一個空字串。因此,在您的程式中,
b = '' # an empty string
split 函式總是回傳一個字串串列。如果在空字串上呼叫,它會回傳一個包含一個元素的串列,即空字串。因此,在您的程式中,
list2 = ['']
這不是一個空串列。它包含 1 個元素。如果將其用作布爾運算式,則其值為 True,因為它包含非零數量的元素。所以:
bool(list2) = True
所以你的 if 運算式if not list2失敗了。如您所見,代碼采用 else 分支,因為您的輸出以文本“Ans:”開頭。
現在,只要其中一個序列結束,zip 函式就會終止。list1 包含 2 個元素,但 list2 僅包含一個元素,因此僅發生 1 次迭代。只列印一個元素。這準確地解釋了你所看到的。
編程需要你去思考和理解每一個細節。
uj5u.com熱心網友回復:
您以錯誤的方式檢查了一個空串列。由于用戶沒有輸入任何內容,因此您無法檢查串列是否為空。或者我應該說該串列不會為空,因為它將等于['']. 您需要檢查輸入是否為空。
a = input("enter the list 1:")
list1 = a.split(",")
print(list1)
b = input("enter the list 2:")
list2 = b.split(",")
if not b: # This is the way of checking if an input is empty or not
print(list1)
else:
res = [i j for i, j in zip(list1,list2)]
print("Ans: ",res)
uj5u.com熱心網友回復:
嘗試這個
if list2 == []:
print(list1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/453144.html
標籤:Python python-3.x 列表
上一篇:繼承的靜態變數
下一篇:使用python實作尾遞回函式
