python小技巧

集合
开发人员常常忘记 Python 也有集合数据类型,大家都喜欢使用列表处理一切。
集合(set)是什么?简单来说就是:集合是一组无序事物的汇集,不包含重复元素。
如果你熟练掌握集合及其逻辑,那么很多问题都可以迎刃而解。举个例子,如何获取一个单词中出现的字母?

myword = "NanananaBatman"
set(myword)
{'N', 'm', 'n', 'B', 'a', 't'}

就这么简单,问题解决了,这个例子就来自 Python 的官方文档,大可不必过于惊讶。
再举一个例子,如何获取一个列表的各个元素,且不重复?

mylist = ["a", "b", "c","c"]

myset = set(mylist)

{'a', 'b', 'c'}

for element in myset:
    print(element)

mynewlist = list(myset)

['a', 'b', 'c']

我们可以看到,“c”元素不再重复出现了。只有一个地方你需要注意,mylist 与 mynewlist 之间的元素顺序可能会有所不同:

mylist = ["c", "c", "a","b"]
mynewlist = list(set(mylist))
# mynewlist is:
['a', 'b', 'c']

枚举有第二个参数
是的,枚举有第二个参数,可能很多有经验的开发人员都不知道。下面我们来看一个例子:

mylist = ['a', 'b', 'd', 'c', 'g', 'e']
for i, item in enumerate(mylist):
    print(i, item)
# Will give:
0 a
1 b
2 d
3 c
4 g
5 e
# but, you can add a start for enumeration:
for i, item in enumerate(mylist, 16):
    print(i, item)
# and now you will get:
16 a
17 b
18 d
19 c
20 g
21 e
posted @ 2021-03-03 15:41  ainimore  阅读(45)  评论(0编辑  收藏  举报