【问题标题】:Working With Multiple Loops Referencing Elements Of Lists使用引用列表元素的多个循环
【发布时间】:2021-03-21 23:43:46
【问题描述】:

我对我所面临的错误做了一个小样本。我实际上需要代码做的是让每个钥匙选择两个任务并将其与钥匙一起打印。当我一开始运行代码时,它似乎可以正常工作,然后就不行了。谁能帮忙。这是输出和代码示例

实际输出

1 + 1 head
1 + 1 head
2 + 2 head
1 + 1 head
2 + 2 leg
1 + 1 head
2 + 2 nose
1 + 1 head
2 + 2 tail
1 + 1 head
list index out of range
pop from empty list
list index out of range
list index out of range
list index out of range
list index out of range
list index out of range
list index out of range

预期输出

1 + 1 head
2 + 2 head
3 + 3 leg
4 + 4 leg
5 + 5 nose
6 + 6 nose
7 + 7 tail
8 + 8 tail

代码

from concurrent.futures import ThreadPoolExecutor, as_completed
keys = ['head','leg','nose','tail']
quest = ['1 + 1','2 + 2','3 + 3','4 + 4','5 + 5','6 + 6','7 + 7' , '8 + 8']
count = []
def solve(i):
    try:
       for h in quest():
         if len(count) != 2:
            q = keys[0]
            print(i,q)
            count.append(q.strip())
    except Exception as e:
       print(e)
t = 2
def run():
    thread = []
    with ThreadPoolExecutor(max_workers=t) as exe:
        for i in quest:
          threads.append(exe.submit(solve,i))
run

【问题讨论】:

  • 在您发布的代码中调用了未知函数quests()。该函数在做什么?
  • @blorgon 没注意到写任务的意思
  • 好的,但你仍在使用函数调用语法,而quest 是一个list 对象...
  • @blorgon 那我怎么知道的呢?
  • 做什么?迭代 list?

标签: python list loops concurrency element


【解决方案1】:
>>> keys = ['head', 'leg', 'nose', 'tail']
>>> quest = ['1 + 1', '2 + 2', '3 + 3', '4 + 4', '5 + 5', '6 + 6', '7 + 7', '8 + 8']
>>> doubled_keys= sum([[*t] for t in zip(keys, keys)], [])
>>> pairs = [*zip(quest, doubled_keys)]
>>> for q, k in pairs:
...     print(q, k)
...
1 + 1 head
2 + 2 head
3 + 3 leg
4 + 4 leg
5 + 5 nose
6 + 6 nose
7 + 7 tail
8 + 8 tail

【讨论】:

  • 它可以工作,但你取出了线程代码,任务有时会超过很多,所以工作需要更快地完成。可以在您的答案中包含线程
猜你喜欢
  • 2020-08-15
  • 1970-01-01
  • 2020-11-14
  • 1970-01-01
  • 2020-07-22
  • 1970-01-01
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多