我需要在API列表上遍历一个列表,更改其值并打印出结果。
my_endpoint = [
'/this/is/endpoint/a',
'/this/is/endpoint/b',
'/this/is/endpoint/c',
'/this/is/endpoint/d',
'/this/is/endpoint/e',
'/this/is/endpoint/f']
change_value = ['1','185','454']
我想使用change_value中的值更改my_endpoint中的“ endpoint”部分。我想要的结果如下:
'/this/is/1/a',
'/this/is/1/b',
'/this/is/1/c',
'/this/is/1/d',
'/this/is/1/e',
'/this/is/1/f']
'/this/is/185/a',
'/this/is/185/b',
'/this/is/185/c',
'/this/is/185/d',
'/this/is/185/e',
'/this/is/185/f']
'/this/is/454/a',
'/this/is/454/b',
'/this/is/454/c',
'/this/is/454/d',
'/this/is/454/e',
'/this/is/454/f']
答案 0 :(得分:0)
请参阅:
my_endpoint = [
'/this/is/endpoint/a',
'/this/is/endpoint/b',
'/this/is/endpoint/c',
'/this/is/endpoint/d',
'/this/is/endpoint/e',
'/this/is/endpoint/f']
change_value = ['1','185','454']
new_lists = {} # dict to hold lists of new values
for line in my_endpoint: # iterate through lines in results from API
for value in change_value: # iterate through list of new values
# check if value is in dict,
# this could be done at the time of creating the dict but this makes it dynamic
if value not in new_lists:
new_lists[value] = [] # add key to dict with empty list as the value
# Use str replace to swap "endpoint" with <value>
# add the new line to a list in the dict using the value as the key
new_lists[value].append(line.replace("endpoint", value))
结果:
new_lists{
'1': ['/this/is/1/a',
'/this/is/1/b',
'/this/is/1/c',
'/this/is/1/d',
'/this/is/1/e',
'/this/is/1/f'
],
'185': ['/this/is/185/a',
'/this/is/185/b',
'/this/is/185/c',
'/this/is/185/d',
'/this/is/185/e',
'/this/is/185/f'
],
'454': ['/this/is/454/a',
'/this/is/454/b',
'/this/is/454/c',
'/this/is/454/d',
'/this/is/454/e',
'/this/is/454/f'
]}