Question about printing multiple items in a list in a specific order in Python

Hellyeah :

So I've been racking my brain on this for a while and decided to reach out to you fine folks. The issue I'm trying to figure out is how to print items in a list in a specific order. I have a list:

m= ['dog','cat','horse','cow','woof','meow','neigh','moo']

And I want to have my results look like this:

'The dog goes woof'
'The cat goes meow'
'The horse goes neigh'
'The cow goes moo'

So far I have tried the following code:

m= ['dog','cat','horse','cow','woof','meow','neigh','moo']

for i in m[:4]:
    print('The ' + i + ' goes ' + str(x for x in m[4:]))

My results are:

'The dog goes <generator object <genexpr> at 0x01177C70>'
'The cat goes <generator object <genexpr> at 0x01177C70>'
'The horse goes <generator object <genexpr> at 0x01177C70>'
'The cow goes <generator object <genexpr> at 0x01177C70>'

Now I found out that the 'x' statement just returns a 'None' value which is why I don't get the results I want. Can anyone give me some insight? Any help will be greatly appreciated. Thanks in advance.

Austin :

You can zip through list:

m = ['dog','cat','horse','cow','woof','meow','neigh','moo']

for x, y in zip(m, m[4:]):
    print(f'The {x} goes {y}')

# The dog goes woof
# The cat goes meow
# The horse goes neigh
# The cow goes moo

For any length list, you can do:

for x, y in zip(m, m[len(m)//2:]):
    print(f'The {x} goes {y}')

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=25606&siteId=1