向列表的每个元素添加引号和方括号



我需要处理一个python列表,如下所示:

PGPrimary=['VDD', 'VSS', 'A', 'Y']

我需要将此列表更改为以下格式:

//PG PRIMARY  ("VDD") ("VSS") ("A") ("Y")

我尝试了以下代码,但它不起作用:

PGPrimary=['VDD', 'VSS', 'A', 'Y']
print("1:PGPrimary:",PGPrimary)
PGPrimary="//PG PRIMARY " + ' '.join(PGPrimary)
(','.join('("' + item + '")' for item in PGPrimary))

print("2:PGPrimary:",PGPrimary)

这是输出:

('1:PGPrimary:', ['VDD', 'VSS', 'A', 'Y'])
('2:PGPrimary:', '//PG PRIMARY VDD VSS A Y')

进程已完成,退出代码为 0

谁能指出为什么代码不起作用?

str.formatstr.join

'//PG PRIMARY  {}'.format(' '.join('("{}")'.format(i) for i in PGPrimary))
  • '("{}")'.format(i) for i in PGPrimary)循环访问列表元素,并在每个元素周围添加括号和引号

  • ' '.join连接上述生成的可迭代对象

例:

In [33]: PGPrimary=['VDD', 'VSS', 'A', 'Y']
In [34]: '//PG PRIMARY  {}'.format(' '.join('("{}")'.format(i) for i in PGPrimary))
Out[34]: '//PG PRIMARY  ("VDD") ("VSS") ("A") ("Y")'

试试这个:

PGPrimary=['VDD', 'VSS', 'A', 'Y']
print("1:PGPrimary:",PGPrimary)
PGPrimary="//PG PRIMARY " + ' '.join('("' + item + '")' for item in PGPrimary)
print("2:PGPrimary:",PGPrimary)

最新更新