[英]Getting elements from a sub-list in Python
I have a .csv file which contains the following 4 lines of elements:我有一个 .csv 文件,其中包含以下 4 行元素:
dev1, NX-OS, 10.0.0.1, admin, admin
dev2, NX-OS, 10.0.0.2, admin, admin
dev3, NX-OS, 10.0.0.3, admin, admin
dev4, NX-OS, 10.0.0.4, admin, admin
I am trying to extract any of the elements.我正在尝试提取任何元素。 In order to do this, I've the following:
为了做到这一点,我有以下几点:
import csv
dev_list=[]
infile=open('dev_in.csv','r')
csv_in=csv.reader(infile)
for dev in csv_in:
dev_list.append(dev)
The result out of dev_list
is the following list of lists: dev_list
的结果是以下列表列表:
[
['dev1, NX-OS, 10.0.0.1, admin, admin'],
['dev2, NX-OS, 10.0.0.2, admin, admin'],
['dev3, NX-OS, 10.0.0.3, admin, admin'],
['dev4, NX-OS, 10.0.0.4, admin, admin']
]
In order to extract the first element of the first list, I coded:为了提取第一个列表的第一个元素,我编码:
element=dev_list[0]
print(element[0])
However, I'm getting the complete first list as a result:但是,我得到了完整的第一个列表:
dev1, NX-OS, 10.0.0.1, admin, admin
Maybe I should split it with the 'split' function but I think that would extend the code unnecessarily.也许我应该用 'split' 函数拆分它,但我认为这会不必要地扩展代码。 What I need to extract the first elements of each sub-list.
我需要提取每个子列表的第一个元素。 However, I may need later to extract other elements.
但是,我稍后可能需要提取其他元素。
Is there another way?还有其他方法吗? Is there also a better way to write this code, maybe with list comprehension Thanks in advance.
是否还有更好的方法来编写此代码,也许可以使用列表理解提前致谢。
Summarizing my comment, here is what you need to do (with Python 3 in mind):总结我的评论,这是您需要做的事情(考虑到 Python 3):
import csv
from pathlib import Path
dev_in = Path('dev_in.csv')
devs = list(csv.reader(dev_in.open(), skipinitialspace=True))
for dev in devs:
# print dev names
print(dev[0])
Code above will give the following lines as output:上面的代码将给出以下几行作为输出:
dev1
dev2
dev3
dev4
Here is a proof of concept:这是一个概念证明:
Python 3.7.5 (default, Dec 15 2019, 17:54:26)
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>> from pathlib import Path
>>> dev_in = Path('dev_in.csv')
>>>
>>> devs = list(csv.reader(dev_in.open(), skipinitialspace=True))
>>> devs
[['dev1', 'NX-OS', '10.0.0.1', 'admin', 'admin'], ['dev2', 'NX-OS', '10.0.0.2', 'admin', 'admin'], ['dev3', 'NX-OS', '10.0.0.3', 'admin', 'admin'], ['dev4', 'NX-OS', '10.0.0.4', 'admin', 'admin']]
>>> dev=devs[0]
>>> dev
['dev1', 'NX-OS', '10.0.0.1', 'admin', 'admin']
>>> dev[0]
'dev1'
>>>
I hope it helps.我希望它有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.