上面代码无法做到轮流输出,能改进一下代码么
时间: 2023-02-10 22:18:31 浏览: 47
可以使用多线程或者使用队列来改进代码。
多线程:
```python
import threading
def print_numbers():
for i in range(1, 11):
print(i)
def print_letters():
for ch in 'abcdefghijklmnopqrstuvwxyz':
print(ch)
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
```
队列:
```python
import threading
import queue
def print_numbers(q):
for i in range(1, 11):
q.put(i)
def print_letters(q):
for ch in 'abcdefghijklmnopqrstuvwxyz':
q.put(ch)
q = queue.Queue()
thread1 = threading.Thread(target=print_numbers, args=(q,))
thread2 = threading.Thread(target=print_letters, args=(q,))
thread1.start()
thread2.start()
while not q.empty():
print(q.get())
thread1.join()
thread2.join()
```
使用多线程或队列,可以让多个函数同时执行并输出,从而达到轮流输出的效果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)