In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces python using numbers and string method skills, which have certain reference value, interested friends can refer to, I hope you have a lot of gains after reading this article, let Xiaobian take you to understand.
1. Use fewer numeric literals
The code below uses numbers as conditional statements, and if you've inherited this code from someone else, it's hard to understand its meaning at first sight.
def mark_trip_as_featured(trip): """Add a trip to the recommendations section """ if trip.source == 11: do_some_thing(trip) elif trip.source == 12: do_some_other_thing(trip) ... ... return
We can use enumeration to make some explanation for these numerical parts.
from enum import IntEnumclass TripSource(IntEnum): FROM_WEBSITE = 11 FROM_IOS_CLIENT = 12def mark_trip_as_featured(trip): if trip.source == TripSource.FROM_WEBSITE: do_some_thing(trip) elif trip.source == TripSource.FROM_IOS_CLIENT: do_some_other_thing(trip) ... ... return
Defining repeated numbers as enumerations not only improves readability, but also reduces the chance of bugs in your code.
Of course, not all numbers need enumeration specifications, such as common numerical subscripts 0 and-1.
You don't have to.
2. Naked string processing problems
"Naked string manipulation" here refers to manipulating strings using only basic addition, subtraction, multiplication, division and loops, in conjunction with built-in functions/methods, to get the results we want.
def fetch_users(conn, min_level=None, gender=None, has_membership=False, sort_field="created"): """Get user list :param int min_level: Minimum user level required, default to all levels :param int gender: Filter user gender, default to all genders :param int has_membership: Filter all member/non-member users, default non-member :param str sort_field: Sort field, default is by created "user created date" :returns: List: [(User ID, User Name),...] """ #An old SQL concatenation trick that uses "WHERE 1=1" to simplify string concatenation operations #Distinguish query params to avoid SQL injection problems statement = "SELECT id, name FROM users WHERE 1=1" params = [] if min_level is not None: statement += " AND level >= ? " params.append(min_level) if gender is not None: statement += " AND gender >= ? " params.append(gender) if has_membership: statement += " AND has_membership == true" else: statement += " AND has_membership == false" statement += " ORDER BY ? " params.append(sort_field) return list(conn.execute(statement, params))
This may seem simple and intuitive, but as function logic becomes more complex, this code becomes error-prone.
A better option is to leverage some open source objectified modules to manipulate them.
SQLAlchemy is used here.
def fetch_users_v2(conn, min_level=None, gender=None, has_membership=False, sort_field="created"): """Get user list """ query = select([users.c.id, users.c.name]) if min_level is not None: query = query.where(users.c.level >= min_level) if gender is not None: query = query.where(users.c.gender == gender) query = query.where(users.c.has_membership == has_membership).order_by(users.c[sort_field]) return list(conn.execute(query))
Other alternative ideas:
Q: Is the target/source string structured and follows a certain format?
Other open source object-oriented modules.
SQL:SQLAlchemy
XML:lxml
JSON、YAML …
Try using a template engine instead of complex string processing logic to achieve your goals.
Jinja2
Mako
Mustache
3. Expand complex computational literal expressions def f1(delta_seconds): #If more than 11 days have passed, do nothing if delta_seconds > 950400: return ...
"Why don't we just write the code if delta_seconds?
< 11 * 24 * 3600: 呢?" "性能",答案一定会是"性能"。 Python 是一门解释型语言,所以预先计算出 950400 正是因为我们不想让每次对函数 f1 的调用都带上这部分的计算开销。 不过事实是:即使我们把代码改成 if delta_seconds < 11 * 24 * 3600:,函数也不会多出任何额外的开销。 当我们的代码中需要出现复杂计算的字面量时,请保留整个算式吧。它对性能没有任何影响,而且会增加代码的可读性。 def f1(delta_seconds): if delta_seconds < 11 * 24 * 3600: return4.实用技巧4.1布尔值也是数字 True 和 False 可以当成 1 和 0 使用 >>> True + 12>>> 1 / FalseTraceback (most recent call last): File "", line 1, in ZeroDivisionError: division by zero
Counting simplifies operations.
>>> l = [1, 2, 4, 5, 7]>>> sum(i % 2 == 0 for i in l)2
If you use a Boolean expression as a subscript to a list, you can achieve something similar to a ternary expression:
#Similar ternary expressions: "Javascript" if 2 > 1 else "Python">>> ["Python", "Javascript"][2 > 1]'Javascript'4.2 improves string readability.
For strings we often use\and + to break strings into several segments.
There is also a simple way to use ().
Then you can use () to open it.
s = ( "There is something really bad happened during the process. " "Please contact your administrator. ")
For multi-indented strings:
Other standard libraries can be invoked to simplify.
from textwrap import dedentdef main(): if user.is_active: # dedent will indent the leftmost empty string of the entire paragraph message = dedent("""\ Welcome, today's movie list: - Jaw (1975) - The Shining (1980) - Saw (2004)""")
Large numbers can also become more readable:
Put an underscore between the numbers.
>>> 10_000_000.0 #Divide the number in thousands 1000000.0>> 0xCAFE_F00D #Hexadecimal digits are also valid, and groups of 4 are more readable 3405705229>> 0b_0011_111_0100_1110 #Binary digits are also valid 16206>> int ('0b_1111_000', 2) #also correctly handles the underscore 2404.3 built-in string functions starting with r when processing strings.
For example, the difference between.split() and.rsplit() is that one splits the string from left to right and the other processes the string from right to left.
The proper use of some ready-made string manipulation functions can make the work more effective.
4.4 float (" inf ")
float ( " inf " ) and float ( " -inf ") correspond to infinity and infinity.
float( " -inf ")
< 任意数值 < float( " inf ") 一些可以用上的场合。 # A. 根据年龄升序排序,没有提供年龄放在最后边>>> users = {"tom": 19, "jenny": 13, "jack": None, "andrew": 43}>>> sorted(users.keys(), key=lambda user: users.get(user) or float('inf'))['jenny', 'tom', 'andrew', 'jack']# B. As the initial value of the loop, simplify the first decision logic>> max_num = float ('-inf')>> #Find the largest number in the list>>> for i in [23, 71, 3, 21, 8]:...: if i > max_num:...: max_num = i...:>>> max_num715. Common Mistake 5.1"value += 1" is not thread safe
This is not a thread safe operation.
This simple accumulation statement is compiled into several different steps, including valuing and saving.
In a multithreaded environment, however, any other thread could cut in at one of these steps and prevent you from getting the right result.
def incr(value): value += 1#view bytecode using dis module import disdis.dis(incr) 0 LOAD_FAST 0 (value) 2 LOAD_CONST 1 (1) 4 INPLACE_ADD 6 STORE_FAST 0 (value) 8 LOAD_CONST 0 (None) 10 RETURN_VALUE
Often dis module to verify their own operation, sometimes, the results and we expected is not the same.
5.2 String concatenation is not slow
Python string concatenation (+=) was slow in 2.2 and earlier.
But later versions have been updated, efficiency has been greatly improved, all string concatenation can still be used.
Thank you for reading this article carefully. I hope that Xiaobian will share the article "What are the skills of python using numbers and strings?" This article is helpful to everyone. At the same time, I hope that everyone will support you a lot and pay attention to the industry information channel. More relevant knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.