我需要編寫一個函數(shù)來返回具有偶數(shù)索引的字符串列表。我在找到一種方法來檢查列表理解中的索引時遇到問題,我嘗試了 index() 但它給了我第一個實例的索引,并且列表不是由唯一字符組成的。這是我到目前為止得到的:def even_chars(st):print(st)if len(st) < 2 or len(st) > 100: return 'invalid string'else: return [s for s in st if st.index(s) % 2 != 0]我正在考慮在 index() 中放置另一個參數(shù),因為它可以從給定的索引開始搜索,但是沒有辦法為每個 s 遞增它。有什么提示嗎?也許我缺少一些內(nèi)置功能?
2 回答

精慕HU
TA貢獻1845條經(jīng)驗 獲得超8個贊
您可以為此使用 enumerate,本質(zhì)上返回當前迭代的編號:
[s for i, s in enumerate(st) if i % 2 == 0]

紫衣仙女
TA貢獻1839條經(jīng)驗 獲得超15個贊
嘗試這個:
#The original string
st = "this is a string"
# Converted into a list
st_list = list(st)
# Print all the elements at even positions
print(st_list[1::2])
這樣你就不需要函數(shù)了。
添加回答
舉報
0/150
提交
取消