避免for循环中的重复

2024-04-26 03:03:57 发布

您现在位置:Python中文网/ 问答频道 /正文

给定此数据结构(大小可变):

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

但这是相当多余的。你知道吗

要达到同样的结果而不重复我自己,最简单的方法是什么?你知道吗


Tags: ofthein数据结构forlenartistitems
3条回答

简单的方法是无条件地使用sample,但是根据输入的长度限制样本大小(因此sample只是洗牌小输入而不减少):

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

行为上不同,因为它也会随机化小列表,但你显然不在乎排序。你知道吗

使用min(是,min,而不是max)设置最大值。你知道吗

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

或者,您可以先保存感兴趣的iterable:

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

请注意,对于长度不同的items,您的代码实际上有不同的行为,因为较长的items随机采样,而较短的items按其原始顺序迭代。你知道吗

您可以尝试:

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

相关问题 更多 >