python初学者_面向初学者的20种重要的Python技巧

python初学者

Python is among the most widely used market programming languages in the world. This is because of a variety of driving factors:

Python是世界上使用最广泛的市场编程语言之一。 这是由于多种驱动因素:

  • It’s simple to understand.

    很容易理解。
  • It’s incredibly versatile.

    它的用途非常广泛。
  • It contains a broad collection of modules and libraries.

    它包含大量的模块和库。

The brevity and higher readability make it quite prominent among all developers.

简洁和更高的可读性使它在所有开发人员中都非常突出。

As a vital part of my job as a data scientist, I use Python every day. Along the way, I’ve gained a few amazing hacks. I’ve listed some of those below.

作为数据科学家工作的重要组成部分,我每天都使用Python。 一路上,我获得了一些惊人的技巧。 我在下面列出了其中一些。

20个必要的Python技巧 (20 Necessary Python Hacks)

1.交换值 (1. Swapping values)

Number swaps normally involve values storage in temporary variables. Yet we could do it by using a single line of code through this Python tip, with no transient variables.

数字交换通常涉及将值存储在临时变量中。 然而,我们可以通过使用此Python技巧中的单行代码来完成此操作,而无需使用瞬态变量。

2.列表中所有项目的一串 (2. One string of all items within a list)

When you have to convolve a string list, you could do this one after another through updating each item with the help of a for loop. It will, nevertheless, be cumbersome, particularly if the list has been lengthy. Within Python, strings are immutable. Thus, in each duo of concatenation, the left and right strings should be copied into a fresh string.

当您需要卷积字符串列表时,可以在for循环的帮助下通过更新每个项目来一个接一个地执行此操作。 但是,这将很麻烦,特别是如果清单很长的话。 在Python中,字符串是不可变的。 因此,在每个串联中,左字符串和右字符串应复制到新字符串中。

Using a join() function, as seen here, is a cleaner solution:

如此处所示,使用join()函数是一种更干净的解决方案:

p = ["Python", "is", "a", "popular", "language"] 
print(" ".join(p))output
Python is a popular language

3.列表中最常见的元素 (3. Most common element in the list)

Identify the most frequently occurring value in a list. If various items occur equally print one of them.

标识列表中最频繁出现的值。 如果各种项目均等出现,请打印其中一项。

Create a list set to remove the redundant values. So the maximum number of events of each item is found in the set, and then we consider the maximum.

创建一个列表集以删除冗余值。 因此,可以在集合中找到每个项目的最大事件数,然后考虑最大值。

list1 = [0, 1, 2, 3, 3, 2, 3, 1, 4, 5, 4] 
print(max(set(list1), key = list1.count))output
3

4.测试两个字符串是否是字谜 (4. Test if two strings are anagrams)

Solve the problems above to figure out whether two strings are anagrams. Given two strings string_1 and string_2, test if both the strings are anagrams of each other.

解决上述问题,找出两个字符串是否为字谜。 给定两个字符串string_1string_2 ,测试两个字符串是否彼此相同。

5.反转字符串 (5. Reverse a string)

Slicing is a handy tip in Python which can also be used to reverse the sequence of items within a string.

切片是Python中的一个方便技巧,它也可以用于反转字符串中的项目顺序。

6.反向列出 (6. Reverse a list)

A copy of the list is created from this approach, and as well, the list is not sorted in order. To create a copy, you need more room to hold all the existing elements.

列表的副本是通过这种方法创建的,并且列表也没有按顺序排序。 要创建副本,您需要更多空间来容纳所有现有元素。

7.转置矩阵 (7. Transpose a matrix)

Transposing a matrix means transforming columns to rows and vice versa. With Python, you can unzip a list that is a transpose of the matrix by using the following code with the zip function in combination with the * tool.

转置矩阵意味着将列转换为行,反之亦然。 使用Python,您可以将以下代码与zip函数结合使用,并结合使用*工具来解压缩作为矩阵转置的列表。

8.链式比较 (8. Chained comparison)

In programming, it is quite normal to test more than two conditions. Let’s assume that we need to test the following:

在编程中,测试两个以上的条件是很正常的。 假设我们需要测试以下内容:

p < q< r

There is indeed a smarter process of writing it with comparison chaining in Python. The operator chaining has been represented as below:

实际上,使用Python中的比较链来编写它确实有一个更聪明的过程。 操作员链表示如下:

if p< q< r:
{.....}

Comparisons return boolean values True or False.

比较返回布尔值TrueFalse

See the example below:

请参阅以下示例:

9.字典'get' (9. Dictionary ‘get’)

Below is a traditional way of accessing a value for a key in Python dictionaries.

以下是在Python词典中访问键值的传统方法。

dict = {"P":1, "Q":2} 
print(dict["P"])
print(dict["R"])

The concern is that the third line of the code yields a key error:

值得关注的是,代码的第三行产生了一个关键错误:

Traceback (most recent call last):
File ".\dict.py", line 3, in
print (dict["R"])
KeyError: 'R'

To prevent these cases, the get() function is used. This technique provides the value for a specific key when available in the dictionary. when it isn’t, None will be returned (if only one argument is used with get()).

为避免这些情况,使用了get()函数。 当在字典中可用时,此技术可提供特定键的值。 否则,将不返回None (如果只有一个参数与get())

10.按值对字典排序 (10. Sort dictionary by value)

Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications, ranging from the competitive domain to the developer domain.

排序一直是日常编程中的有用工具。 Python词典广泛用于从竞争领域到开发人员领域的许多应用程序中。

Construct a dictionary, as well as show all keys in alphabetical order. List both the alphabetically sorted keys and values by the value.

构造一个字典,并按字母顺序显示所有键。 列出按字母顺序排序的键和按值列出的值。

11.清单理解 (11. List comprehension)

To construct fresh lists from different iterables, list comprehensions are used. Since list comprehensions yield lists, they contain parentheses that include the expression which gets executed to every element. List comprehension is simpler, as the Python interpreter is designed to detect a recurring pattern in looping.

为了从不同的可迭代对象构造新的列表,使用列表推导。 由于列表推导产生列表,因此它们包含的括号包括对每个元素执行的表达式。 列表理解更简单,因为Python解释器旨在检测循环中的重复模式。

12.实施计划的一部分所花费的时间 (12. Time consumed to implement a part of the program)

This one focuses on showing how to compute the time taken by the program or a section of a program to execute. Calculating time helps to optimize your Python script to perform better.

本节重点介绍如何计算程序或程序的一部分执行所花费的时间。 计算时间有助于优化Python脚本以使其表现更好。

13.合并字典 (13. Merge dictionaries)

This is a trick in Python where a single expression is used to merge two dictionaries and store the result in a third dictionary. The single expression is **. This does not affect the other two dictionaries. ** implies that the argument is a dictionary. Using ** is a shortcut that allows you to pass multiple arguments to a function directly by using a dictionary.

这是Python中的一个技巧,其中单个表达式用于合并两个字典并将结果存储在第三个字典中。 单个表达式是** 。 这不会影响其他两个词典。 **表示该参数是字典。 使用**是一种快捷方式,它允许您通过使用字典将多个参数直接传递给函数。

Using this, we first pass all the elements of the first dictionary into the third one and then pass the second dictionary into the third. This will replace the duplicate keys of the first dictionary.

使用此方法,我们首先将第一个字典的所有元素传递给第三个字典,然后将第二个字典传递给第三个字典。 这将替换第一个字典的重复键。

14.数字化 (14. Digitize)

Here is the code that uses map(), list comprehension, and a simpler approach for digitizing.

这是使用map() ,列表理解和一种更简单的数字化方法的代码。

15.测试唯一性 (15. Test for uniqueness)

Some list operations require us to test when total items in the list are distinct. This usually happens when we try to perform the set operations in a list. Hence, this particular utility is essential at these times.

一些列表操作要求我们测试列表中的总项目何时不同。 当我们尝试在列表中执行设置操作时,通常会发生这种情况。 因此,此特定实用程序在这些时候至关重要。

16.使用枚举 (16. Using enumeration)

Using enumerators, finding an index is quick when you’re within a loop.

使用枚举器,当您处于循环中时,可以快速找到索引。

17.在一行中评估任意数字的阶乘 (17. Evaluate the factorial of any number in a single line)

This one gives you a method to find the factorial of a given number in one line.

这为您提供了一种在一行中查找给定数字的阶乘的方法。

18.返回几个函数的元素 (18. Return several functions’ elements)

This function is not offered by numerous computer languages. For Python, though, functions yield several elements.

许多计算机语言均未提供此功能。 但是,对于Python,函数产生几个元素。

Kindly review the following instance to understand how it performs.

请查看以下实例以了解其性能。

19.合并一个真实的Python switch-case语句 (19. Incorporate a true Python switch-case statement)

Below is the script used to replicate a switch-case structure with a dictionary.

下面是用于复制带有字典的切换案例结构的脚本。

20.使用splat运算符解包函数参数 (20. With splat operator unpacking function arguments)

The splat operator provides an efficient way of unpacking lists of arguments. For clarification, please go through the following illustration:

splat运算符提供了一种解压缩参数列表的有效方法。 为了澄清起见,请检查下图:

尾注 (The Ending Note)

I hope the aforementioned 20 necessary Python hacks will allow you to accomplish your Python jobs swiftly and effectively. You can further consider those or your assignments and programs.

我希望前面提到的20个必要的Python技巧可以使您快速有效地完成Python工作。 您可以进一步考虑这些或您的作业和程序。

Some I found while browsing the Python Standard Library docs. A few others I found searching through PyTricks.

我在浏览Python标准库文档时发现的一些。 我发现其他一些人通过PyTricks进行搜索。

If you think I should include more or have suggestions, please do comment below.

如果您认为我应该包括更多内容或有建议,请在下面做评论。

Thanks for reading!

谢谢阅读!

翻译自: https://medium.com/better-programming/20-valuable-and-essential-python-hacks-for-beginners-112954560aff

python初学者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值