《笨方法学PYTHON》——twentiethlesson

习题40:字典,可爱的字典

针对列表,特性如下:

things = ['a', 'b', 'c', 'd']
print("第二个元素为:", things[1])
things[1] = 'z'
print("替换后的第二个元素为:", things[1])
print('替换后的列表:', things)
第二个元素为: b
替换后的第二个元素为: z
替换后的列表: ['a', 'z', 'c', 'd']

字典的简单特性如下:

stuff = {'name': 'Zed', 'age': 36, 'height': 6 * 12 + 2}
print('key为name的值:', stuff['name'])
print('key为age的值:', stuff['age'])
print('key为height的值:', stuff['height'])
stuff['city'] = 'San Francisco'
stuff['age'] = 23
print('新增的key为city的值:', stuff['city'])
print('更改的key为age的值:', stuff['age'])
stuff[1] = 'Wow'
stuff[2] = 'Neato'
print('新增key为1,整型非字符型,它的值:', stuff[1])
print('新增key为2,整型非字符型,它的值:', stuff[2])
print('该字典为:',stuff)
del stuff['city']
del stuff[1]
del stuff[2]
print('该字典为:',stuff)
key为name的值: Zed
key为age的值: 36
key为height的值: 74
新增的key为city的值: San Francisco
更改的key为age的值: 23
新增key为1,整型非字符型,它的值: Wow
新增key为2,整型非字符型,它的值: Neato
该字典为: {'name': 'Zed', 'age': 23, 'height': 74, 'city': 'San Francisco', 1: 'Wow', 2: 'Neato'}
该字典为: {'name': 'Zed', 'age': 23, 'height': 74}

我这个IDE也是神奇了,输出竟然按键入的顺序输出了。。。本来想对这输出说一个字典的特性的,但字典还是有这么一个特性:字典是没有顺序的

# cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville','NY':'New York','OR':'Portland'}
cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'


# 字典查的是key,不查value
def findCity(themap, state):
    if state in themap:
        return themap[state]
    else:
        return 'Not found.'


# ok pay attention!
# 调用函数不带括号时,是取的函数本身,即函数在内存中的地址
cities['_find'] = findCity
while True:
    print('State?(ENTER to quit)')
    state = input("> ")
    # 对于字符串,none为False,有字符就为True
    if not state: break
    # this line is the most important ever!study!
    cityFound = cities['_find'](cities, state)
    print(cityFound)

print(cities)

1. 在 Python 文档中找到 dictionary (又被称作 dicts, dict)的相关的内容,学着对 dict 做更多的操作。

2. 找出一些 dict 无法做到的事情。例如比较重要的一个就是 dict 的内容是无序的,你可以检查一下看看是否真是这样。

3. 试着把 for-loop 执行到 dict 上面,然后试着在 for-loop 中使用 dict 的 items() 函数,看看会有什么样的结果。

for city in cities.items():
    print(city)

print_r('点个赞吧');
var_dump('点个赞吧');
NSLog(@"点个赞吧!")
System.out.println("点个赞吧!");
console.log("点个赞吧!");
print("点个赞吧!");
printf("点个赞吧!\n");
cout << "点个赞吧!" << endl;
Console.WriteLine("点个赞吧!");
fmt.Println("点个赞吧!")
Response.Write("点个赞吧");
alert(’点个赞吧’)

猜你喜欢

转载自blog.csdn.net/qq_41470573/article/details/84820967