【问题标题】:Looping over a list with another list changing it's values in Python用另一个列表循环遍历一个列表,改变它在 Python 中的值
【发布时间】:2019-03-19 13:55:17
【问题描述】:

我需要在 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 中的“端点”部分。我想要的结果如下:

'/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']

【问题讨论】:

  • 你有没有尝试过,例如一个简单的 for 循环?

标签: python loops


【解决方案1】:

见:


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'
]}

【讨论】:

  • 谢谢technoman5000。 dict 不适合我的目的,所以我不得不调整它以使用列表,但嵌套循环效果很好。
猜你喜欢
  • 2022-01-06
  • 1970-01-01
  • 2019-09-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-26
  • 1970-01-01
  • 1970-01-01
  • 2017-04-09
相关资源
最近更新 更多