简体   繁体   中英

How to create a list from urls that was concatenated in a loop?

My goal is put all my urls into a list. I had concatenate them after looping through a number list, as an example:

The code that I've written:

number_list = [1, 2, 3]
url_list = []

for i in number_list:
  url_string_concat = 'www.example.url/=' + str(i)
  url_list.append(url_string_concat)

  print(url_list)

I expected output to be:

  url_list = ['www.example.url/=1', 'www.example.url/=2', 'www.example.url/=3']

However, the result that I obtain was:

['www.example.url/=1'] ['www.example.url/=1', 'www.example.url/=2'] ['www.example.url/=1', 'www.example.url/=2', 'www.example.url/=3']

Is there something that I'm missing here?

Because you're calling print on every iteration

number_list = [1, 2, 3]
url_list = []

for i in number_list:
    url_string_concat = 'www.example.url/=' + str(i)
    url_list.append(url_string_concat)

print(url_list)

output

['www.example.url/=1', 'www.example.url/=2', 'www.example.url/=3']

or you can simplify your code with list comprehension:

url_list = ['www.example.url/={}'.format(i) for i in range(1, 4)]

output:

url_list
['www.example.url/=1', 'www.example.url/=2', 'www.example.url/=3']

Your print statement occurs on every iteration. Here would be adding in a print statement at the end of the iteration as well -- which is where your expected result would occur:

number_list = [1, 2, 3]
url_list = []
for i in number_list:
    url_string_concat = 'www.example.url/=' + str(i)
    url_list.append(url_string_concat)
    print("Running num %s ==> %s" % (i, url_list))


print ("Done ==> %s" % url_list)

And you'd get:

Running num 1 ==> ['www.example.url/=1']
Running num 2 ==> ['www.example.url/=1', 'www.example.url/=2']
Running num 3 ==> ['www.example.url/=1', 'www.example.url/=2', 'www.example.url/=3']
Done ==> ['www.example.url/=1', 'www.example.url/=2', 'www.example.url/=3']

Your code is okay, the list is concatenated correctly, but you print it on every iteration so you see as it is growing. @frankegoesdown showed you a corrected code. You can also use list comprehensions

url_list = ['www.example.url/=' + str(i) for i in range(1, 4)]
print(url_list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM