我在保證長度至少為 2 的字串串列strs中有前兩個字串。我想將它們的字母相互比較,并在它們的字母相同時執行任務。這是我正在使用的代碼:
iter_len = len(strs[1])
if (len(strs[0]) >= len(strs[1])):
iter_len = len(strs[0])
for i in range (0, iter_len, 1):
if (strs[0][i] == strs[1][i]):
[do a thing]
但是,當我運行它時,我得到了一條IndexError: string index out of range線if (strs[0][i] == strs[1][i]):。我不太明白為什么會發生這種情況,因為第一條if陳述句應該確保它是anditer_len之間的最小長度,并且應該防止索引超出。非常感謝任何建議。strs[0]strs[1]
uj5u.com熱心網友回復:
如果您需要以鎖步方式迭代兩個序列,通常最佳做法是使用zip:
for a,b in zip(strs[0], strs[1]):
if a == b:
#[do a thing]
這將解決一個序列比另一個序列長的問題。
如果你需要索引,你可以使用enumerate你的zip:
for i, (a, b) in enumerate(zip(strs[0], strs[1])):
if a == b:
#[do a thing with i]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/468161.html
上一篇:如何將每個第一個唯一的多索引設定為0并為其他索引計算值
下一篇:為字典串列中的每個專案分配字典值
