避免重複:在爲(在大小可變的)給定的這種數據結構環
items = [(u'Triathalon ', u' Teenager'), (u'The Airplanes ', u' Paper Hearts'), (u"Holy '57 ", u' Island Kids'), (u'Yohuna ', u' Apart'), (u'Moon Bounce ', u' Shake'), (u'Miami Horror ', u' Wild Motion (Set It Free)'), (u'Colleagues ', u' Somewhere'), (u'Poor Spirits ', u' BwooKlyn'), (u'Air Review ', u' Young'), (u'Radiohead', u'Karma Police')]
我想這樣做:
if len(items) > 10:
for artist, track in random.sample(items, 10):
# do a lot of things in many lines of code
elif len(items) < 10:
for artist, track in items:
# do the exact same thing
但這是相當冗餘的。
實現相同結果而不重複自己的最簡單方法是什麼?
你確實意識到你現有的代碼不處理'len(items)== 10'的情況,對吧?據推測,如果你確實使用了代碼,那麼你的'elif'語句應該只是一個'else'的情況,沒有條件測試。 – ShadowRanger
注意,將解決它。 –