帮助在 python 中查找 csv 中的项目

发布于 2024-11-17 14:02:24 字数 496 浏览 2 评论 0原文

我是Python新手。我有一个不变的 csv,这是一个示例(我只是在 python 控制台中按行打印了它)

['george', 'williams', '277389', 'susan thompson', '2042228888']
['john', 'smith', '833999', 'george smith', '2041118833']
['michael', 'jackson', '281038', 'ronald jackson', '2041128493']

字段标题

['firstname', 'lastname', 'idnumber', 'emergency contact', 'emerg contact ph']

这些是我需要能够输入 id 号的 ,这会启动对 csv 的搜索,并输出个人的名字、姓氏、紧急联系人、电话号码。有什么想法吗?我真的需要知道从哪里开始,即我是否应该将 csv 的内容读入字典中

I'm very novice in python. I have an unchanging csv, here's an example (I just printed it by row in the python console)

['george', 'williams', '277389', 'susan thompson', '2042228888']
['john', 'smith', '833999', 'george smith', '2041118833']
['michael', 'jackson', '281038', 'ronald jackson', '2041128493']

these are the field titles

['firstname', 'lastname', 'idnumber', 'emergency contact', 'emerg contact ph']

I need to be able to type in the id number, which initiates a search through the csv, and outputs the individual's firstname, lastname, emergency contact, phone number. Any thoughts? I really need to know where to start, i.e., should I read the contents of the csv into a dict

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

时光清浅 2024-11-24 14:02:24

我个人会选择字典:

records = [
    ['george', 'williams', '277389', 'susan thompson', '2042228888'],
    ['john', 'smith', '833999', 'george smith', '2041118833'],
    ['michael', 'jackson', '281038', 'ronald jackson', '2041128493'],
    ]

from operator import itemgetter
recordsbyid = dict(zip(map(itemgetter(2),records),records))

然后您可以执行

>>> recordsbyid['277389']
['george', 'williams', '277389', 'susan thompson', '2042228888']

itemgetter 选择第二个元素(id),map 适用于每条记录,zip将 ids 与其记录连接成由 (id,record) 组成的元组列表。 dict 将其转换为字典。

I would personally go with a dictionary:

records = [
    ['george', 'williams', '277389', 'susan thompson', '2042228888'],
    ['john', 'smith', '833999', 'george smith', '2041118833'],
    ['michael', 'jackson', '281038', 'ronald jackson', '2041128493'],
    ]

from operator import itemgetter
recordsbyid = dict(zip(map(itemgetter(2),records),records))

then you can do

>>> recordsbyid['277389']
['george', 'williams', '277389', 'susan thompson', '2042228888']

itemgetter selects the second element (id), map applies to every record, and zip concatenates the ids with their records into a list of tuples consisting of (id,record). dict turns this into a dictionary.

陌若浮生 2024-11-24 14:02:24

我会将此 csv 转换为 sqlite 并使用查询:

SELECT * FROM data WHERE idnumber = %s

我喜欢使用数据库中组织的数据,它可能会在未来为您带来更多优势(更复杂的查询)。

要将 cvs 转换为 sqlite 并测试查询,请使用 适用于 Firefox 的 SQLite Manager 插件< /a>.

I would convert this csv to sqlite and use a query:

SELECT * FROM data WHERE idnumber = %s

I like working with the data organized in DB and it might bring you more advantages in the future (more sophisticated queries).

To convert the cvs to sqlite and test queries use SQLite Manager addon for Firefox.

孤独难免 2024-11-24 14:02:24

如果您需要扫描文件并仅查找所需的行一次,则无需将所有数据转换为字典 - 只需逐行读取行,直到找到您的行:

import csv

def find_row_by_id(filename, key_column, id):
    with f = open(filename, 'rb'):
        my_reader = csv.reader(f)
        for row in my_reader:
            if row[key_column] == id:
                return row
    raise Error("Could not find row")

print find_by_row('eggs.csv', 2, my_id) # my_id should by a string

如果您的文件很小并且您需要仅通过 id 进行多次搜索,按照其他答案的建议将其转换为字典。

另一方面,如果您的文件非常(非常)大并且您需要进行快速查找和/或多次查找,请首先将您的 csv 文件读入键值数据库: 适用于 Linux 的可靠且高效的键值数据库?

If you need to scan the file and find the required row just once, you don't need to convert all data into a dictionary - just read the lines one by one until you find your row:

import csv

def find_row_by_id(filename, key_column, id):
    with f = open(filename, 'rb'):
        my_reader = csv.reader(f)
        for row in my_reader:
            if row[key_column] == id:
                return row
    raise Error("Could not find row")

print find_by_row('eggs.csv', 2, my_id) # my_id should by a string

If your file is small and you need to do multiple searches only by id, convert it to a dictionary as suggested by other answers.

On the other hand, if your file is very (very) big and you need to make fast look ups and/or many look ups, read your csv file into a key-value database first: Reliable and efficient key--value database for Linux?

帅气尐潴 2024-11-24 14:02:24

使用 raw_input 获取所需的 id

当你拥有它时,使用 if 语句来查看 id 是否匹配:

Where line is ['george', 'williams', '277389', 'susan thompson', '2042228888']

if line[2] == id:
    for x in line:
        if not x == line[2]:
            print x

希望它有帮助!

Use raw_input to get the wanted id.

When you have it use an if statement to see if the id matches:

Where line is ['george', 'williams', '277389', 'susan thompson', '2042228888']

if line[2] == id:
    for x in line:
        if not x == line[2]:
            print x

Hope it helps!

落日海湾 2024-11-24 14:02:24

让我们首先将每一行制作成一个字典,使用字段标题作为键,使用字段数据作为值。我们想要一个字典,其中每个键值对都来自我们通过将这两个列表“压缩”在一起而获取的对:dict(zip(field_titles, row))。我们可以使用列表理解从输入行列表中创建这些字典的列表:[dict(zip(field_titles, row)) for row in data]

我们希望能够通过 id_number 查找这些内容,因此我们将创建一个包含字典,其中键是 idnumber,值是行字典。我们可以通过在 row_dict 中查找来获取 idnumber:dict((row_dict['id_number'], row_dict) for row_dict in data)

Let's make each line into a dict first, using the field titles as keys and the field data as values. We want a dict where each key-value pair comes from a pair that we grab by "zipping" those two lists together: dict(zip(field_titles, row)). We can use a list comprehension to make a list of these dicts from the list of input rows: [dict(zip(field_titles, row)) for row in data].

We want to be able to look these up by id_number, so we'll make a containing dict where the key is the idnumber and the value is the row dict. We can get the idnumber by looking it up in the row_dict: dict((row_dict['id_number'], row_dict) for row_dict in data).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文