2017-03-03 24 views
-1

避免重複:在爲(在大小可變的)給定的這種數據結構環

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 

但這是相當冗餘的。

實現相同結果而不重複自己的最簡單方法是什麼?

+0

你確實意識到你現有的代碼不處理'len(items)== 10'的情況,對吧?據推測,如果你確實使用了代碼,那麼你的'elif'語句應該只是一個'else'的情況,沒有條件測試。 – ShadowRanger

+0

注意,將解決它。 –

回答

2

你可以嘗試做:

for artist, track in random.sample(items,min(10,len(items))): 
# do something 
0

也許你想numpy.random.choice

import numpy.random as npr 

slice = npr.choice(items, 10, replace=False) 
for artist, track in slice: 
    # do whatever 
3

平凡的方法是使用sample無條件的,但限制基於輸入的長度的樣本大小(因此sample只是洗牌小輸入而不降低):

for artist, track in random.sample(items, min(len(items), 10)): 

在行爲上不同,因爲它也將小列表隨機化,但你顯然不關心排序。

1

使用min(是,min,而不是max)設置最大值。

for artist, track in random.sample(items, min(10, len(items))): 

或者,您也可以保存迭代你感興趣的第一:

if len(items) > 10: 
    i = random.sample(items, 10) 
else: 
    i = items 
for artist, track in i: 

請注意,您的代碼實際上有不同的行爲不同長度的items,作爲一個較長的items被隨機抽取,而按照原始順序迭代較短的一個。

0

您可以將random.sample放在公用代碼之前。

items = [...] 

if len(items) > 10: 
    real_items = random.sample(items, 10): 
else: 
    real_items = items 

然後做任何你與real_items

0
請問

這對你的工作?

samplesize = 10 if len(items) > 10 else len(items) 
sample = random.sample(items, samplesize) 
for artist, track in sample: 
    ....