英文:
Print named tuple value in a list
问题
一个函数返回给我以下命名元组的列表:
[popenfile(path='/home/giampaolo/monit.py', fd=3, position=0, mode='r', flags=32768), popenfile(path='/var/log/monit.log', fd=4, position=235542, mode='a', flags=33793)]
我想打印元组中 'path' 的值。怎么做?请帮帮我,亲爱的社区。
我尝试了遵循在线文章,但没有解决。
英文:
A function is returning me the below list of named tuples:
[popenfile(path='/home/giampaolo/monit.py', fd=3, position=0, mode='r', flags=32768), popenfile(path='/var/log/monit.log', fd=4, position=235542, mode='a', flags=33793)]
I want to print the value of 'path' in the tuple. How to do this? Please help dear community.
I tried to follow online articles but no solve.
答案1
得分: 1
为了明确起见,请参阅以下代码:
from collections import namedtuple
popenfile = namedtuple('popenfile', 'path fd position mode flags')
tuple_list = [popenfile(path='/home/giampaolo/monit.py', fd=3, position=0, mode='r', flags=32768), popenfile(path='/var/log/monit.log', fd=4, position=235542, mode='a', flags=33793)]
for ntup in tuple_list:
print(ntup.path)
这段代码会输出:
/home/giampaolo/monit.py
/var/log/monit.log
英文:
To make it clear see below code:
from collections import namedtuple
popenfile = namedtuple('popenfile', 'path fd position mode flags')
tuple_list = [popenfile(path='/home/giampaolo/monit.py', fd=3, position=0, mode='r', flags=32768), popenfile(path='/var/log/monit.log', fd=4, position=235542, mode='a', flags=33793)]
for ntup in tuple_list:
print(ntup.path)
which prints
/home/giampaolo/monit.py
/var/log/monit.log
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论