Python类别-Set&删除方法? [英] Python class - Set & Delete methods?

查看:138
本文介绍了Python类别-Set&删除方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我想提一下,我是Python的新手,我发现从C ++过渡有点困难。

First I'd like to mention that I am completely new to Python and I've found it a bit difficult to transition from C++. I apologize if my question comes off as elementary.

我有一个针对歌曲的类,对此我进行了以下初始化。它从包含歌曲ID,名称,流派等文件的文件中获取数据,所有文件均由 :: 分隔。

I have a class for 'songs' which I have initialized as following. It takes in data from a file that contains a song's ID, name, genre etc. all separated by ::.

    def __init__(self):
            self.song_names = dict()
            self.song_genres = dict()

    def load_songs(self,  song_id):
            f = open(song_id)
            for line in f:
                    line = line.rstrip()
                    component = line.split("::")
                    sid = components[0]
                    same= components[1]
                    sgenre=components[2]
            self.song_names[mid] = sname
            self.song_genres[mid] = sgenre
            f.close()

该程序还从文件中获取数据带有用户信息,以
UserID :: Gender :: Age :: Occupation :: Zip 等分隔,并带有 ratings文件。

The program also takes in data from a file with 'users' information, separated as UserID::Gender::Age::Occupation::Zip etc. and a file with 'ratings'.

我会实现一个功能,例如 def set_song(sid,list((title,genres)))
等等 delete_song(sid)吗?

I would I implement a function like def set_song(sid, list((title,genres))) and something like delete_song(sid) ?

我将不得不完成更多其他功能,但是如果有人可以帮助我这两个-至少对结构和语法有更好的了解-处理其他应该更容易。

I'm going to have to wind up doing a ton more other functions, but if someone could help me with those two - at least to have a better idea of structure and syntax - handling the others should be easier.

推荐答案

为什么不只是从字典继承并使用其接口?这样,您可以使用Python的标准映射操作来代替自己滚动:

Why not just inherit from dict and use its interface? That way you can use Python's standard mapping operations instead of rolling your own:

class Songs(dict):

    def load(self, song_id):
        with open(song_id, 'r') as f:
            for line in f:
                sid, name, genre = line.rstrip().split('::')[:3]
                self[sid] = [name, genre]

mysongs = Songs()
mysongs.load('barnes_and_barnes__fish_heads')
mysongs['barnes_and_barnes__fish_heads'] = ['roly poly', 'strange']  # set
del mysongs['barnes_and_barnes__fish_heads']                         # delete

这篇关于Python类别-Set&删除方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆