简体   繁体   English

Python-动态填充变量

[英]Python - Dynamically Populate Variable

Suppose I have the following data in read.txt: 假设我在read.txt中包含以下数据:

_app1_ip_
_app2_ip_
_app1_ip_
_app3_ip_
_app2_ip_

And I want to replace each with a certain corresponding value (in this case, the values in 'list') and output that to another file (out.txt): 我想将每个值替换为某个对应的值(在这种情况下为“列表”中的值),然后将其输出到另一个文件(out.txt):

list = ['app1', 'app2', 'app3']

for l in list:
   field = '_%s_ip_' %l

   patterns = {
      field : l,
   }

   with open("read.txt", "r") as my_input:
      content = my_input.read()
   with open("out.txt", "w+") as my_output:
      for i,j in patterns.iteritems():
         content = content.replace(i,j)
         my_output.write(content)

What I want is the following in data.txt: 我想要的是data.txt中的以下内容:

app1
app2
app1
app3
app2

What I actually get is: 我实际上得到的是:

_app1_ip_
_app2_ip_
_app1_ip_
app3
_app2_ip_

This seems so simple.. would be an easy one-liner in bash/sed. 这似乎很简单..在bash / sed中很容易实现。 Can anyone please help/explain? 谁能帮忙/解释一下?

After

list = ['app1', 'app2', 'app3']
for l in list:
    field = '_%s_ip_' %l
    patterns = {
        field : l,
    }

patterns only contains the last value, ie patterns仅包含最后一个值,即

patterns = {'_app3_ip_': 'app3'}

because you overwrite patterns in every loop iteration. 因为您在每次循环迭代中都会覆盖patterns Instead, you want to populate that dictionary. 而是要填充该词典。 You can either do that with a for loop like you used: 您可以使用for循环来执行此操作,如您所使用的:

list = ['app1', 'app2', 'app3']
patterns = {}
for l in list:
    field = '_%s_ip_' % l
    patterns[field] = l

or by using a dictionary comprehension: 或使用字典理解:

patterns = {'_%s_ip_' % l: l for l in ['app1', 'app2', 'app3']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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