我有一个非常具体的用例来创建列表理解,但我在弄清楚如何做到这一点上有些困难.我相信一定有一个方法或函数可以帮助我,但我猜我没有意识到它.
以下是场景: 下面的代码按照预期工作并生成所有预期的变化(总共8个)
List_A = ["apples","oranges"]
List_B = ["meat","chicken"]
flexibility = range(2)
list = []
for a in List_A:
结果s = [(day, b, a) for day in flexibility for b in List_B]
list.append(结果s)
print (list)
结果
[[(0, 'meat', 'apples'), (0, 'chicken', 'apples'), (1, 'meat', 'apples'), (1, 'chicken', 'apples')],
[(0, 'meat', 'oranges'), (0, 'chicken', 'oranges'), (1, 'meat', 'oranges'), (1, 'chicken', 'oranges')]]
Here is the complication. Let's assume I have a rate limit of 5 calls per second, and the list above creates 8 elements, hence I would go above the rate limit. The way I thought I could overcome this, was to create another variable to pass on to the function that will use a different accounts to make my api request. In theory, each account would make only 5 requests. Thus in my example above, the first 5 elements of the list would have account 0 and the rest 3 would use account 1. I tried using list comprehension to achieve this, but the 结果 is not what I expected:
no = [0,1,2]
List_A = ["apples","oranges"]
List_B = ["meat","chicken"]
flexibility = range(2)
list = []
for a in List_A:
结果s = [(day, b, a,n) for day in flexibility for b in List_B for n in no]
list.append(结果s)
print (list)
结果s
[[(0, 'meat', 'apples', 0), (0, 'meat', 'apples', 1), (0, 'meat', 'apples', 2), (0, 'chicken', 'apples', 0), (0, 'chicken', 'apples', 1), (0, 'chicken', 'apples', 2), (1, 'meat', 'apples', 0), (1, 'meat', 'apples', 1), (1, 'meat', 'apples', 2), (1, 'chicken', 'apples', 0), (1, 'chicken', 'apples', 1), (1, 'chicken', 'apples', 2)],
[(0, 'meat', 'oranges', 0), (0, 'meat', 'oranges', 1), (0, 'meat', 'oranges', 2), (0, 'chicken', 'oranges', 0), (0, 'chicken', 'oranges', 1), (0, 'chicken', 'oranges', 2), (1, 'meat', 'oranges', 0), (1, 'meat', 'oranges', 1), (1, 'meat', 'oranges', 2), (1, 'chicken', 'oranges', 0), (1, 'chicken', 'oranges', 1), (1, 'chicken', 'oranges', 2)]]
我的 list 中的元素比我想要的要多得多.我仍然想要原来的8,但前5个将使用帐户0,最后3个帐户1.
我们的目标是得到这份名单:
[(0, 'apples', 'meat',0),
(0, 'apples', 'chicken',0),
(0, 'oranges', 'meat',0),
(0, 'oranges', 'chicken',0),
(1, 'apples', 'meat',0),
(1, 'apples', 'chicken',1),
(1, 'oranges', 'meat',1),
(1, 'oranges', 'chicken',1)]
我怎样才能做到这一点呢? 谢谢