简体   繁体   English

使用Python将变量添加到列表中

[英]Add a variable into a list with Python

I want add a variable to some of the items in mylist = ['A', 'B', 'C', 'D', 'E']. 我想向mylist = ['A','B','C','D','E']中的某些项目添加变量。 I tried something like this example... 我尝试了类似这个例子的东西...

for direction in ['Up', 'Down']:
    mylist = ['A{}', 'B', 'C{}', 'D', 'E'].format(direction)
    for x in mylist:
        print x

I want the output to be the following... 我希望输出如下...

AUp
B
CUp
D
E
ADown
B
CDown
D
E

However, this isn't working. 但是,这不起作用。 Is there a best way to add a variable in a list? 有没有在列表中添加变量的最佳方法?

You cannot "vectorize" this formatting operation! 您不能“矢量化”此格式化操作! It should be operated upon each string individually. 应该对每个字符串分别进行操作。

data = ['A{}', 'B', 'C{}', 'D', 'E']
direction = ['Up', 'Down']

for d in direction:
     print(*[x.format(d) for x in data], sep='\n')

AUp
B
CUp
D
E
ADown
B
CDown
D
E

Iterate over direction , and call format in a loop. 遍历direction ,并循环调用format If you're using python3, you can use the * iterable unpacking with a sep argument. 如果您使用的是python3,则可以将*可迭代解压缩与sep参数一起使用。

For python2, add a __future__ import statement at the top of your file, like this - 对于python2,在文件顶部添加__future__ import语句,如下所示-

from __future__ import print_function

You can then use the print function to the same effect. 然后,您可以使用print功能达到相同的效果。

I would do this 我会这样做

mylist = ['A{}', 'B', 'C{}', 'D', 'E']
for direction in ['Up', 'Down']:
    for x in mylist:
        x = x.format(direction)
        print(x)

With keeping the original mylist : 保留原始的mylist

mylist = ['A', 'B', 'C', 'D', 'E']
for direction in ['Up', 'Down']:
    for x in mylist:
        print x + direction if x in ['A', 'C'] else x

I have little different approach , You can do without loop without using two loop in just one line but result will be in list format : 我几乎没有什么不同的方法,您可以不循环而不用仅在一行中使用两个循环,但是结果将是列表格式:

 print(list(map(lambda x:list(map(lambda y:y.format(x),data)),direction)))

output: 输出:

[['AUp', 'B', 'CUp', 'D', 'E'], ['ADown', 'B', 'CDown', 'D', 'E']]

But if you want each element in new line then you have to iterate : 但是,如果要换行中的每个元素,则必须进行迭代:

for k in direction:
    for i in data:
        print(i.format(k))

output: 输出:

AUp
B
CUp
D
E
ADown
B
CDown
D
E

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

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