0

I have a hash table in python and I have a lot of data and some are the same but I need to chain them.

I want to make a music database which if I search some numeric values called HZ i could find the name of the song.

So lets say I have a song Called Song 1 I measure it HZ values but their are countless 10 to be specific.

What I want to make is to have the ability to search any HZ value and have the same result.

Song 1
10 HZ 
20 HZ
30 HZ
40 HZ
50 HZ
60 HZ
70 HZ
80 HZ
90 HZ
100 HZ

So if I input any of these 10 values i would get the name Song 1 as results

4

4 回答 4

0

只需使用内置字典。对于大多数用例,它比您自己编写的任何代码都高效得多。

听起来您想要的只是将歌曲名称存储为每个赫兹值的值。如果您有多首歌曲共享一个赫兹,您可以使用存储集合的字典(或只是一个默认字典)。

于 2013-09-01T03:18:20.977 回答
0

我会使用 a dictwith lists 作为值来存储数据。尝试类似:

music = {10: [<Song 1>, <Song 3>],
         20: [<Song 1>, <Song 2>]
        }

现在要查看所有具有 10HZ 的歌曲,只需使用:

music[10]
于 2013-09-01T03:18:51.107 回答
0

在您的字典(“哈希表”)中输入所有 HZ 值作为相同的键'Song 1'。很可能不止一首歌曲与另一首歌曲具有相同的 HZ 值。在这种情况下,您希望将不同的歌曲与同一个 HZ 保持在集合中,因此您的字典的值是歌曲集合而不是单个歌曲。实现这一目标的最简单方法是:

    from collections import defaultdict
    musicDirectory= defaultdict(set)

    musicDirectory[ 10].add( 'Song 1' )
    musicDirectory[ 40].add( 'Song 1' )
    musicDirectory[ 70].add( 'Song 1' )
    musicDirectory[100].add( 'Song 1' )
    musicDirectory[ 10].add( 'Song 2' )
    musicDirectory[ 70].add( 'Song 2' )
    musicDirectory[ 50].add( 'Song 2' )
    musicDirectory[ 10].add( 'Song 3' )
    musicDirectory[ 50].add( 'Song 3' )
    musicDirectory[ 70].add( 'Song 3' )

    print(40,"HZ=",musicDirectory[10])
    print(70,"HZ=",musicDirectory[10])

应该打印:

    40 HZ= {'Song 1'}
    70 HZ= {'Song 2', 'Song 3', 'Song 1'}

因为只有一首歌HZ=40,但是三首HZ=70。

于 2013-09-01T03:21:10.630 回答
0

假设我有 10 首歌曲,每首歌曲都有一个频率,但只有 5 个可能的独特频率:

In [18]: import numpy as np

In [19]: from collections import defaultdict

In [20]: songs = [''.join(np.random.choice(list(letters), size=10).tolist()) for _ in range(10)]

In [21]: freqs = np.random.choice(range(10, 15), size=10).tolist()

In [22]: data = defaultdict(list)

In [23]: for freq, song in zip(freqs, songs):
   ....:     data[freq].append(song)
   ....:

In [24]: dict(data)
Out[24]:
{10: ['qlogxhxscp', 'eqxaeiyujp', 'wnhyprymyq', 'snsqquyvmv'],
 11: ['toibbjljxi', 'lqdxucnrpv', 'mrxxwmnxil'],
 13: ['lxcpzbswxx'],
 14: ['gmdbimcwon', 'zafhszrwss']}

或者,如果一首歌可以有多个频率,则使用 aset而不是 a 。list

于 2013-09-01T04:15:46.567 回答