避免for循环中的重复

时间:2017-03-03 02:44:45

标签: python for-loop conditional

给出这个数据结构(大小可变):

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

但这是多余的。

在不重复自己的情况下,获得相同结果的最简单方法是什么?

6 个答案:

答案 0 :(得分:3)

琐碎的方法是无条件地使用sample,但是根据输入的长度限制样本大小(所以sample只是在不减少的情况下随机播放小输入):

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

行为不同,因为它也会随机化小名单,但你显然不关心订购。

答案 1 :(得分:2)

您可以尝试:

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

答案 2 :(得分:1)

使用while (strcmp(clrChoice, "nochange") != 0) { break; } while (strcmp(clrChoice, "gray") != 0) { system("COLOR 8"); break; } while (strcmp(clrChoice, "blue") != 0) { system("COLOR 1"); break; } while (strcmp(clrChoice, "lightblue") != 0) { system("COLOR 9"); break; } while (strcmp(clrChoice, "green") != 0) { system("COLOR 2"); break; } while (strcmp(clrChoice, "lightgreen") != 0) { system("COLOR A"); break; } while (strcmp(clrChoice, "aqua") != 0) { system("COLOR 3"); break; } while (strcmp(clrChoice, "lightaqua") != 0) { system("COLOR B"); break; } while (strcmp(clrChoice, "red") != 0) { system("COLOR 4"); break; } while (strcmp(clrChoice, "lightred") != 0) { system("COLOR C"); break; } while (strcmp(clrChoice, "purple") != 0) { system("COLOR 5"); break; } while (strcmp(clrChoice, "lightpurple") != 0) { system("COLOR D"); break; } while (strcmp(clrChoice, "yellow") != 0) { system("COLOR 6"); break; } while (strcmp(clrChoice, "lightyellow") != 0) { system("COLOR E"); break; } while (strcmp(clrChoice, "white") != 0) { system("COLOR 7"); break; } while (strcmp(clrChoice, "brightwhite") != 0) { system("COLOR F"); break; } (是的,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会被随机采样,而较短的代码会按原始顺序进行迭代。

答案 3 :(得分:0)

也许你想要numpy.random.choice

import numpy.random as npr

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

答案 4 :(得分:0)

您可以将random.sample放在公共代码之前。

items = [...]

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

然后用real_items做任何事情

答案 5 :(得分:0)

这对你有用吗?

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