python 在线

941Python 列表(List)

针对列表无法正常输出汉字的解决方法:

#encoding=utf-8

import json

list_words = [ '你', '我', '他' ]
print( list_words )                                        # 无法正常显示汉字
print( str(list_words).decode( 'string_escape' ) )         # 正常显示汉字

list_words_result = json.dumps( list_words, encoding='UTF-8', ensure_ascii=False )
print( list_words_result )

输出结果为:

['\xe4\xbd\xa0', '\xe6\x88\x91', '\xe4\xbb\x96']
['你', '我', '他']
["你", "我", "他"]

940Python 列表(List)

列表里 aa[:] 不同。

我们可以通过函数 id() 来查看:

a = [1, 2, 3]
id(a)
id(a[:])

会发现得到的两个值不同。

或者直接运行:

a is a[:]

返回值将是:False

简单来说,a[:] 是创建 a 的一个副本,这样我们在代码中对 a[:] 进行操作后,就不会改变 a 的值了。而若直接对 a 进行操作,那么 a 的值会收到一些操作的影响,如 append() 等。

939Python 列表(List)

[:-1] 表示从第一个元素遍历到倒数第二个元素:

# -*- coding: UTF-8 -*-

list1 = [1,2,3,4,5,]

print list1

# 列表截取
print list1[:-1]

输出结果:

[1, 2, 3, 4, 5]
[1, 2, 3, 4]

938Python 列表(List)

遍历嵌套的列表:

num_list = [[1,2,3],[4,5,6]]
for i in num_list:
    for j in i:
        print(j)

输出结果:

1
2
3
4
5
6

937Python 列表(List)

>>> list4=[123,["das","aaa"],234]
>>> list4
>>> "aaa" in list4                  #in只能判断一个层次的元素
False
>>> "aaa" in list4[1]           #选中列表中的列表进行判断
True
>>> list4[1][1]
'aaa'