30个你想打包带走的Python技巧(上)
与上述技巧相反,我们可以根据字符串列表创建字符串,然后在各个单词之间加入空格: mylist = ['The', 'quick', 'brown', 'fox'] mystring = " ".join(mylist) print(mystring) # 'The quick brown fox' 你可能会问为什么不是 mylist.join(” “),这是个好问题! 根本原因在于,函数 String.join() 不仅可以联接列表,而且还可以联接任何可迭代对象。将其放在String中是为了避免在多个地方重复实现同一个功能。 13. 表情符有些人非常喜欢表情符,而有些人则深恶痛绝。我在此郑重声明:在分析社交媒体数据时,表情符可以派上大用场。 首先,我们来安装表情符模块: pip3 install emoji 安装完成后,你可以按照如下方式使用: import emoji result = emoji.emojize('Python is :thumbs_up:') print(result) # 'Python is 👍' # You can also reverse this: result = emoji.demojize('Python is 👍') print(result) # 'Python is :thumbs_up:' 更多有关表情符的示例和文档,请点击此处(https://pypi.org/project/emoji/)。 14. 列表切片列表切片的基本语法如下: a[start:stop:step] start、stop 和 step 都是可选项。如果不指定,则会使用如下默认值:
示例如下: # We can easily create a new list from # the first two elements of a list: first_two = [1, 2, 3, 4, 5][0:2] print(first_two) # [1, 2] # And if we use a step value of 2, # we can skip over every second number # like this: steps = [1, 2, 3, 4, 5][0:5:2] print(steps) # [1, 3, 5] # This works on strings too. In Python, # you can treat a string like a list of # letters: mystring = "abcdefdn nimt"[::2] print(mystring) # 'aced it' 15. 反转字符串和列表你可以利用如上切片的方法来反转字符串或列表。只需指定 step 为 -1,就可以反转其中的元素: revstring = "abcdefg"[::-1] print(revstring) # 'gfedcba' revarray = [1, 2, 3, 4, 5][::-1] print(revarray) # [5, 4, 3, 2, 1] 原文链接:https://towardsdatascience.com/30-python-best-practices-tips-and-tricks-caefb9f8c5f5 (编辑:青岛站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |