循环遍历python列表和字符串格式

时间:2019-08-07 15:50:33

标签: python string string-formatting

以字符串格式的列表循环列表

我有以下变量

BUILDING = "123"
SIDE = "ProductionA"
TODO = "traveling without moving"

我有以下列表

OS = ["Linux", "Unix", "Windows"]

我创建一个格式化的字符串列表

FLIST = [
"I am installing in {}, side {} using the {} cd".format (BUILDING,SIDE,o),
"Other random stuff",
"Even more random stuff: ".format(TODO)]

我想循环播放列表:

for o in OS:
    print(o)
    for f in FLIST:
        print(f)

我希望得到:

"I am installing in 123, side ProductionA using the Linux cd"
"Other random stuff",
"Even more random stuff: traveling without moving"

"I am installing in 123, side ProductionA using the Unix cd"
"Other random stuff",
"Even more random stuff: traveling without moving"

"I am installing in 123, side ProductionA using the Windows cd"
"Other random stuff",
"Even more random stuff: traveling without moving"

print(o)可以正常工作,如果我省略格式字符串中的OS,我将获得值(LinuxUnixWindow)。

I am installing in {}, side {} using the {} cd".format (BUILDING,SIDE)

但是格式化列表不接受o变量,我得到的错误是:

  

NameError:未定义名称'o'。

感谢您的帮助。

3 个答案:

答案 0 :(得分:4)

我已将FLIST放入循环中。尝试

BUILDING = "123"
SIDE = "ProductionA"
TODO = "traveling without moving"

OS = ["Linux", "Unix", "Windows"]

for o in OS:
    print(o)
    FLIST = ["I am installing in {}, side {} using the {} cd".format (BUILDING,SIDE,o),"Other random stuff","Even more random stuff: {}".format(TODO)]
    for f in FLIST:
        print(f)

输出:

Linux
I am installing in 123, side ProductionA using the Linux cd
Other random stuff
Even more random stuff: traveling without moving
Unix
I am installing in 123, side ProductionA using the Unix cd
Other random stuff
Even more random stuff: traveling without moving
Windows
I am installing in 123, side ProductionA using the Windows cd
Other random stuff
Even more random stuff: traveling without moving

查看实际情况here

答案 1 :(得分:3)

say "2" cmp "10"; # More 应该以{{1​​}}作为输入的功能:

'A' … 'AA'

答案 2 :(得分:2)

尝试创建以o作为参数的函数FLIST

def FLIST(o):
    return [
        "I am installing in {}, side {} using the {} cd".format (BUILDING,SIDE,o), 
        "Other random stuff",
        "Even more random stuff: ".format(TODO)
    ]

然后使用此功能:

for o in OS:
    print(o)
    for f in FLIST(o):
        print(f)