我想要如下所示的输出:

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

有什么线索吗?

===============>>#1 票数:2

使用enumerate

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

===============>>#2 票数: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

===============>>#3 票数: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)

===============>>#4 票数: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和隐式代码:website =“ google facebook yahoo”

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

这也可以,但是请记住以下规则:

显式比隐式更好

  ask by Kumar translate from so

未解决问题?本站智能推荐: