Python 避免for循环中的重复
给定此数据结构(大小可变): 我想这样做:Python 避免for循环中的重复,python,for-loop,conditional,Python,For Loop,Conditional,给定此数据结构(大小可变): 我想这样做: 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 如果长度(项目)>10: 对于
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
如果长度(项目)>10:
对于艺术家,随机跟踪。样本(项目10):
#用很多行代码做很多事情
elif len(项目)<10:
对于艺术家,跟踪项目:
#做同样的事
但这是相当多余的
在不重复自己的情况下获得相同结果的最简单方法是什么?也许你想要
简单的方法是无条件地使用
sample
,但根据输入的长度限制样本大小(因此sample
只洗牌小输入而不减少):
行为不同,因为它也会随机化小列表,但您显然不关心排序。使用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:
请注意,对于不同长度的
项
,您的代码实际上具有不同的行为,因为较长的项
将随机采样,而较短的项将按其原始顺序迭代。您可以将random.sample放在公共代码之前
items = [...]
if len(items) > 10:
real_items = random.sample(items, 10):
else:
real_items = items
然后对真实物品执行任何操作您可以尝试:
for artist, track in random.sample(items,min(10,len(items))):
# do something
这对你有用吗
samplesize = 10 if len(items) > 10 else len(items)
sample = random.sample(items, samplesize)
for artist, track in sample:
....
您知道您现有的代码不能处理
len(items)==10的情况,对吗?假设,如果您确实使用了该代码,那么您的elif
语句应该只是一个没有条件测试的else
案例。注意,将修复它。
items = [...]
if len(items) > 10:
real_items = random.sample(items, 10):
else:
real_items = items
for artist, track in random.sample(items,min(10,len(items))):
# do something
samplesize = 10 if len(items) > 10 else len(items)
sample = random.sample(items, samplesize)
for artist, track in sample:
....