Split Pairs
問題描述:
Split the string into pairs of two characters. If the string contains an odd number of characters, then the missing second character of the final pair should be replaced with an underscore ('_').
(將一個字符串兩兩分開,最后如果剩一個就加上“_”重新組成一對)
Input:?A string.
Output:?An iterable of strings.
def split_pairs(a):# your code herereturn Noneif __name__ == '__main__':print("Example:")print(list(split_pairs('abcd')))# These "asserts" are used for self-checking and not for an auto-testingassert list(split_pairs('abcd')) == ['ab', 'cd']assert list(split_pairs('abc')) == ['ab', 'c_']assert list(split_pairs('abcdf')) == ['ab', 'cd', 'f_']assert list(split_pairs('a')) == ['a_']assert list(split_pairs('')) == []print("Coding complete? Click 'Check' to earn cool rewards!")對我來說這有點難,split不能用,那就只能用索引,最終有了以下比較繁瑣的方法:?
def split_pairs(a):# your code herelst=[]lst_index=0if len(a)%2==0:for i in range(len(a)//2):lst.append(a[lst_index:lst_index+2])lst_index+=2elif len(a)%2==1:for i in range(len(a)//2):lst.append(a[lst_index:lst_index+2])lst_index+=2lst.append(a[-1]+'_')return lst其他解決方案:
一:對我上面想法的一個更優版。
def split_pairs(a):# your code hereif a == '':return []if len(a) % 2 == 1:a = a + "_"b = [a[i:i+2] for i in range(0, len(a), 2)]return b?
二:很簡單的一行,但是用了zip,一個對我來說新的知識點。
def split_pairs(a):return [ch1+ch2 for ch1,ch2 in zip(a[::2],a[1::2]+'_')]官方文檔解釋:
zip(*iterables)
創建一個聚合了來自每個可迭代對象中的元素的迭代器。
返回一個元組的迭代器,其中的第?i?個元組包含來自每個參數序列或可迭代對象的第?i?個元素。 當所輸入可迭代對象中最短的一個被耗盡時,迭代器將停止迭代。 當只有一個可迭代對象參數時,它將返回一個單元組的迭代器。 不帶參數時,它將返回一個空迭代器。
也就是說兩個列表中的相同索引會在一起。而當上面輸入的一個偶數長度的字符串時,多余的'_'并不會被組合到一起,這個真的是很厲害。
三:還有一個新的庫,textwrap文本自動換行與填充
from textwrap import wrapdef split_pairs(a):a = a + '_' if len(a) % 2 else areturn wrap(a, 2)?textwrap?模塊提供了一些快捷函數,以及可以完成所有工作的類?TextWrapper。 如果你只是要對一兩個文本字符串進行自動換行或填充,快捷函數應該就夠用了;否則的話,你應該使用?TextWrapper?的實例來提高效率。
textwrap.wrap(text,?width=70,?*,?initial_indent="",?subsequent_indent="",?expand_tabs=True,?replace_whitespace=True,?fix_sentence_endings=False,?break_long_words=True,?drop_whitespace=True,?break_on_hyphens=True,?tabsize=8,?max_lines=None)
對?text?(字符串) 中的單獨段落自動換行以使每行長度最多為?width?個字符。 返回由輸出行組成的列表,行尾不帶換行符。
這個也是處理這個問題很好的方法。
總結
以上是生活随笔為你收集整理的Split Pairs的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电脑如何剪辑视频?自学视频剪辑的朋友看过
- 下一篇: R语言-数据排序