python如何创建可互换值列表?

编程入门 行业动态 更新时间:2024-10-28 10:31:27
本文介绍了python如何创建可互换值列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在处理Midi音符,midi编号和频率.我应该使用python中的哪种列表来引用任何一个属性并获取其他属性?

I'm working with midi note, midi number, and frequency. What kind of list in python should I use to refer to any one attribute and get the other attributes?

例如:

  • 输入:"C3",返回frequency并获得261.6255653006.

输入:261.6255653006,返回midinumber并获得60

输入:60,返回midinote并获得"C3"

我将使用什么语法,函数,对象或列表类型?

what syntax, functions, objects, or list type would I use?

推荐答案

就像我在评论中说的那样,您可能正在寻找元组字典.示例:

Like I said in the comments, a dictionary of tuples is what you're probably looking for. Example:

data = {'C3': ('frequency', 261.6255653006), 261.6255653006: ('midinumber', 60), 60: ('midinote', 'C3'), }

要验证您的输入,您可以执行以下操作:

To validate your input you can do:

input = raw_input() try: key = float(input) except ValueError: key = input try: value = data[key] except KeyError: print "Invalid input. Valid keys are: " + ', '.join(data.keys()) else: #input was valid, so value == data[key]

对索引进行索引就像对列表进行索引一样.但是,它们是不可变的,这意味着您无法更改它们或将新项目添加到它们.我相信您的情况就是如此.

Tuples are indexed just like lists are. However, they are immutable which means you can't change them or append new items to them. And I believe that's desired in your case.

字典通过键索引,例如data['C3']返回('frequency', 261.6255653006),而data['C3'][0]返回'frequency'.

Dictionaries are indexed by keys, for example data['C3'] returns ('frequency', 261.6255653006) and data['C3'][0] returns 'frequency'.

更多推荐

python如何创建可互换值列表?

本文发布于:2023-10-07 20:03:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1470399.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!