Python中的字典与成员运算符初步探究

yipeiwu_com5年前Python基础

Python元字典
字典(dictionary)是除列表以外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。
两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
字典用"{ }"标识。字典由索引(key)和它对应的值value组成。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print dict['one'] # 输出键为'one' 的值
print dict[2] # 输出键为 2 的值
print tinydict # 输出完整的字典
print tinydict.keys() # 输出所有键
print tinydict.values() # 输出所有值

输出结果为:

This is one This is two {'dept': 'sales', 'code': 6734, 'name': 'john'} ['dept', 'code', 'name'] ['sales', 6734, 'john']

Python成员运算符
除了以上的一些运算符之外,Python还支持成员运算符,测试实例中包含了一系列的成员,包括字符串,列表或元组。

以下实例演示了Python所有成员运算符的操作:

#!/usr/bin/python

a = 10
b = 20
list = [1, 2, 3, 4, 5 ];

if ( a in list ):
  print "Line 1 - a is available in the given list"
else:
  print "Line 1 - a is not available in the given list"

if ( b not in list ):
  print "Line 2 - b is not available in the given list"
else:
  print "Line 2 - b is available in the given list"

a = 2
if ( a in list ):
  print "Line 3 - a is available in the given list"
else:
  print "Line 3 - a is not available in the given list"

以上实例输出结果:

Line 1 - a is not available in the given list
Line 2 - b is not available in the given list
Line 3 - a is available in the given list

相关文章

导入tensorflow:ImportError: libcublas.so.9.0 报错

导入tensorflow:ImportError: libcublas.so.9.0 报错

错误:ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory...

Mac在python3环境下安装virtualwrapper遇到的问题及解决方法

前言 我在使用mac安装virtualwrapper的时候遇到了问题,搞了好长时间,才弄好,在这里总结一下分享出来,供遇到相同的问题的朋友使用,少走些弯路。 问题说明: Mac默认系...

python实现批量改文件名称的方法

本文实例讲述了python实现批量改文件名称的方法。分享给大家供大家参考。具体分析如下: 发现python中提供了大量的模块函数,有时候一些系统操作在python中非常简单 下面的文件关...

用TensorFlow实现多类支持向量机的示例代码

用TensorFlow实现多类支持向量机的示例代码

本文将详细展示一个多类支持向量机分类器训练iris数据集来分类三种花。 SVM算法最初是为二值分类问题设计的,但是也可以通过一些策略使得其能进行多类分类。主要的两种策略是:一对多(one...

在Django的URLconf中使用多个视图前缀的方法

在实践中,如果你使用字符串技术,特别是当你的 URLconf 中没有一个公共前缀时,你最终可能混合视图。 然而,你仍然可以利用视图前缀的简便方式来减少重复。 只要增加多个 pattern...