展开列表Python中的变量

时间:2014-03-20 13:11:38

标签: python list

需要知道如何在列表元素中扩展变量

  >>> one_more = "four"
  >>> var_names = ["one", "two", "three_<expand variable one_more>"]

应该像

一样
  ['one', 'two', 'three_four']

2 个答案:

答案 0 :(得分:2)

非常基本:

In [1]: a="four"    
In [2]: b="five"
In [3]: ['one', 'two', 'three_%s' % a]
Out[3]: ['one', 'two', 'three_four']

您还可以将变量加入列表:

In [5]: ['one', 'two', 'three_%s' % '_'.join((a,b))]
Out[5]: ['one', 'two', 'three_four_five']

这是与str.format相同的解决方案:

In [6]: ['one', 'two', 'three_{}'.format('_'.join((a,b)))]
Out[6]: ['one', 'two', 'three_four_five']

答案 1 :(得分:0)

我认为你想在列表中进行字符串替换。这是一个符合您要求的示例。

one_more = "four"
var_names = ["one", "two", "three_<var>"]

print [x.replace("<var>", one_more) for x in var_names]

>>> ["one", "two", "three_four"]

如果您想一次替换多个模式,可以执行以下操作:

a = "AA"
b = "BB"
var_names = ["one", "two", "three_$a", "four_$b"]

def batch_replace(str, lookup):
   for pattern in lookup:
      replacement = lookup[pattern]
      str = str.replace(pattern, replacement)
   return str

print [batch_replace(x, {"$a": a, "$b": b}) for x in var_names] 

>>> ["one", "two", "three_AA", "four_BB"]