带有一些字符串的嵌套循环如何在python中工作?

时间:2015-05-17 10:50:43

标签: python python-2.7 python-3.x

我想要输出如下所示:

The website is google number 1
The website is facebook number 2
The website is yahoo number 3

google facebook yahoo'来自列表,数字应从1增加到3。

我尝试了以下python代码:

websites = "google facebook yahoo"
for web in websites.split( ):
    n=0
    while n < 3:
        n=n+1
        print web,n

我得到的输出如下所示:

C:\Users\test\Desktop>python nested_loop_in_python.py
google 1
google 2
google 3
facebook 1
facebook 2
facebook 3
yahoo 1
yahoo 2
yahoo 3

C:\Users\test\Desktop>

但我需要输出:

The website is google number 1
The website is facebook number 2
The website is yahoo number 3

有任何线索吗?

4 个答案:

答案 0 :(得分:2)

使用enumerate

for index, site in enumerate(websites.split(),1):
  print(site, index) 

答案 1 :(得分:1)

首先替换:

print web,n

通过

print ("The website is " + web + " number " + str(n))

和第二,替换:

for web in websites.split():
    n=0
    while n < 3:
        n=n+1

由:

n=0
for web in websites.split():
    n=n+1

您将获得您期望的结果。要缩短代码并使其更加pythonic,我建议您使用enumerate

答案 2 :(得分:1)

使用enumeratehttps://docs.python.org/2/library/functions.html#enumerate):

websites = "google facebook yahoo"
for j, web in enumerate(websites.split(' '), start=1):
    print 'The website is {0} number {1}'.format(web, j)

答案 3 :(得分:0)

另一种方法:

websites = "google facebook yahoo"

l = websites.split()

for w, i in zip(l, range(len(l))):
    print 'The website is {0} number {1}'.format(w,i+1)

我可以避免像这样使用l和隐式代码:     网站=&#34; google facebook yahoo&#34;

for w, i in zip(websites.split(), range(len(websites.split()))):
    print 'The website is {0} number {1}'.format(w,i+1)

这也可以,但要记住这条规则:

  

明显比隐含更好