python如何并列运行两个for循环

Python020

python如何并列运行两个for循环,第1张

需要用到多线程

#!/usr/bin/python3

import _thread

import time

# 为线程定义一个函数

def print_time( threadName, delay):

....count = 0

....while count <5:

........time.sleep(delay)

........count += 1

........print ("%s: %s" % ( threadName, time.ctime(time.time()) ))

# 创建两个线程

try:

...._thread.start_new_thread( print_time, ("Thread-1", 2, ) )

...._thread.start_new_thread( print_time, ("Thread-2", 4, ) )

except:

....print ("Error: 无法启动线程")

while 1:

....time.sleep(5)

....print('is main ')

这一段效果和下面这个代码块是一样的。

temp = []

for line in f:

    for word in line.split():

        temp.append(word)

print len(temp)

我不知道你是在什么地方看到这样的例子的,但你没必要再看了。把简单的东西复杂化一点也不高大上。而且这段代码也实现不了求文本中非空白字符数目的功能。line=' hello'或者'hello '或者'he llo'这三种情况都得不到正确结果。

python中的for循环和c中的for循环意义不同,python中for循环是迭代,如果要加入条件,要在for中嵌套if条件语句,

如果循环设两个变量的话可以这样:

for

i

in

range(1,10):

for

j

in

range(2,100):

print(i,j)

或者利用元组

for

(i,j)

in

[(1,2),(2,3),(4,5)]:

print(i,j)