给定此数据结构(大小可变):
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
但这是相当多余的。你知道吗
要达到同样的结果而不重复我自己,最简单的方法是什么?你知道吗
简单的方法是无条件地使用
sample
,但是根据输入的长度限制样本大小(因此sample
只是洗牌小输入而不减少):行为上不同,因为它也会随机化小列表,但你显然不在乎排序。你知道吗
使用
min
(是,min
,而不是max
)设置最大值。你知道吗或者,您可以先保存感兴趣的iterable:
请注意,对于长度不同的
items
,您的代码实际上有不同的行为,因为较长的items
随机采样,而较短的items
按其原始顺序迭代。你知道吗您可以尝试:
相关问题 更多 >
编程相关推荐