每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg
今日推荐开源项目:《GitHub 上什么都有.jpg lists》传送门:GitHub链接
推荐理由:一个 GitHub 上各种列表的列表,你可以在这个列表中发现各种各样的事物(尽管它们中的有些非常……奇怪),从技术类的 React 各种工具,到非技术类的婴儿睡眠指南,再到列表的列表的列表的列表的列表的列表,最后一个我真的没打错不信可以去看看这个项目的最后面,真的是六个。
或者可以直接通过这个链接直达:https://github.com/enedil/awesome-awesome-awesome-awesome-awesome-awesome
今日推荐英文原文:《Five Python Tricks You Need to Know Today》作者:Enoch CK
原文链接:https://towardsdatascience.com/five-python-tricks-you-need-to-learn-today-9dbe03c790ab
推荐理由:使用 Python 时写代码的一些小技巧,兴许有些会对你有所帮助
Five Python Tricks You Need to Know Today
Whether you are a senior AI engineer or a first-year biology student, you will come across the Python programming language at some point. First released in 1991, Python has quickly become the favorite language used by programmers and technologists. Based on Stack Overflow question views in high-income countries, Python is found to be rapidly becoming the most popular language of choice.
The Incredible Growth of Python- David Robinson
Being a high-level, interpreted language with a relatively easy syntax, Python is perfect even for those who don’t have prior programming experience. Popular Python libraries are well integrated and used in diverse fields such as bioinformatics (biopython), data science (pandas), machine learning (keras/ tensorflow) and even astronomy (astropy). After learning C and Java as my first programming languages, I was able to teach myself Python within weeks of googling it. Despite executing much slower than Java and other languages, Python actually improves productivity by having well-built process integration features.
Before we get started, I highly recommend you to check out Dan Bader’s Python Tricks Book. In his book, Dan has shared some really informative tips and tricks about how to code more efficiently in Python. If you do not know Python at all, I highly suggest you to get started with Code Academy’s Learn Python interactive course.
Trick №1: Powerful One-Liners
Are you tired of reading through lines of code and getting lost in conditional statements? Python one-liners might just be what you are looking for. For example, the conditional statements
>>> if alpha > 7:>>> beta = 999>>> elif alpha == 7:>>> beta = 99>>> else:>>> beta = 0
can really be simplified to:
>>> beta = 999 if alpha > 7 else (beta == 99 if alpha == 7 else 0)
This is ridiculous! Should you pay more attention to the code you wrote, you’d always find places where you can simplify as one-liners. Besides conditional statements, for
loops can also be simplified too. For example, doubling a list of integer in four lines
>>> lst = [1, 3, 5]>>> doubled = [] >>> for num in lst:>>> doubled.append(num*2)
can be simplified to just one line:
>>> doubled = [num * 2 for num in lst]
Of course, it might get a bit messy if you chain everything into one-liners. Make sure you aren’t overusing one-liners in your code, as one might argue that the extensive use of one-liners is “un-Pythonic”.
>>> import pprint; pprint.pprint(zip(('Byte', 'KByte', 'MByte', 'GByte', 'TByte'), (1 << 10*i for i in xrange(5))))
Trick №2: Quick String Manipulations
String manipulations can be tricky (no pun intended), but Python has hidden shorthands to make your life significantly easier. To reverse a string, we simply add ::-1
as list indices
>>> a = "ilovepython" >>> print a[::-1] nohtypevoli
The same trick can be applied to a list of integers as well. String manipulation is extremely easy in Python. For example, if you want to output a sentence using the following predefined variables str1
, str2
and lst3
>>> str1 = "Totally">>> str2 = "Awesome">>> lst3 = ["Omg", "You", "Are"]
Simply use the .join()
method and arithmetic operators to create the desired sentence.
>>> print ' '.join(lst3)Omg You Are>>> print ' '.join(lst3)+' '+str1+' '+str2Omg You Are Totally Awesome
Besides string manipulation, I also recommend reading more about regex (regular expressions) to effectively search through strings and filter patterns.
Trick №3: Nested Lists Combination
itertools
is probably one of my favorite Python library. Imagine your code had a dozen of lists and after some manipulation, you ended up with a deeply nested list. itertools
is exactly what you need to resolve this syntactical mess.
>>> import itertools>>> flatten = lambda x: list(itertools.chain.from_iterable(x))>>> s = [['"', 'An', 'investment'], ['in'], ['knowledge'], ['pays'], ['the', 'best'], ['interest."', '--'], ['Benjamin'], ['Franklin']]>>> print(' '.join(flatten(s)))" An investment in knowledge pays the best interest." -- Benjamin Franklin
As you can see from the example above, we can combine nested lists and strings using .join()
and itertools
. .combinations()
method in itertools
is also a powerful tool to return the length subsequences of elements from the input iterable. Click here to read more about itertools
.
Trick №4: Simple Data Structures
Going back to Trick №1, it is also very easy to use one-liner to initialize data structures in Python. Harold Cooper has implemented a one-liner tree structure using the following code:
>>> def tree(): return defaultdict(tree)
The code shown above simply defines a tree that is a dictionary whose default values are trees. Other one-liner functions such as prime number generator
>>> reduce( (lambda r,x: r-set(range(x**2,N,x)) if (x in r) else r), range(2,N), set(range(2,N)))
can be found all over Github and Stack Overflow. Python also has powerful libraries such as Collections
, which will help you to solve a variety of real-life problems without writing lengthy code.
>>> from collections import Counter>>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3]>>> print(Counter(myList))Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})
Trick №5: Printing Made Easy
The last trick is something I wish I had known earlier. Turns out to print an array with strings as one comma-separated string, we do not need to use .join()
and loops.
>>> row = ["1", "bob", "developer", "python"]
>>> print(','.join(str(x) for x in row))
1,bob,developer,python
This simple one-liner will do:
>>> print(*row, sep=',')
1,bob,developer,python
Another neat printing trick is to make use of enumerate
. enumerate
is a built-in function of Python which is incredibly useful. So instead of writing a four-line code to print
>>> iterable = ['a','b','c'] >>> c = 0 >>> for item in iterable: >>> print c, item >>> c+= 1 0 a 1 b 2 c
The same can be done under just two lines
>>> for c, item in enumerate(iterable): >>> print c, item
There are hundreds of thousands of printing tricks in Python such as pretty printing pprint
. Comment below if you know a slick Python trick!
每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/Opening
代码格式出现了问题 😉 ,大佬修复一下
@可乐: 多谢提醒 已修复