我需要处理如下的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
任何人都可以指出代码无效的原因吗?
答案 0 :(得分:2)
str.format
和str.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")'
答案 1 :(得分:1)
试试这个:
PGPrimary=['VDD', 'VSS', 'A', 'Y']
print("1:PGPrimary:",PGPrimary)
PGPrimary="//PG PRIMARY " + ' '.join('("' + item + '")' for item in PGPrimary)
print("2:PGPrimary:",PGPrimary)