python生成一系列数字_一系列有用的Python技巧

python生成一系列数字

Python is one of the world’s most popular, in-demand programming languages. This is for many reasons:

Python是世界上最受欢迎的按需编程语言之一。 这有很多原因:

  • it’s easy to learn

    很容易学习
  • it’s super versatile

    超级通用
  • it has a huge range of modules and libraries

    它具有大量的模块和库

I use Python daily as an integral part of my job as a data scientist. Along the way, I’ve picked up a few useful tricks and tips.

我每天都将Python用作数据科学家工作的组成部分。 一路上,我学到了一些有用的技巧和窍门。

Here, I’ve shared some of them in an A-Z format.

在这里,我以AZ格式分享了其中的一些内容。

Most of these ‘tricks’ are things I’ve used or stumbled upon during my day-to-day work. Some I found while browsing the Python Standard Library docs. A few others I found searching through PyPi.

这些“窍门”大部分是我在日常工作中曾经使用或偶然发现的东西。 我在浏览Python标准库文档时发现的一些。 我发现其他一些人通过PyPi搜索。

However, credit where it is due — I discovered four or five of them over at awesome-python.com. This is a curated list of hundreds of interesting Python tools and modules. It is worth browsing for inspiration!

但是,应归功于我–我在awesome-python.com上发现了其中的四五个。 这是数百种有趣的Python工具和模块的精选列表。 值得浏览以获取灵感!

全部或任何 (all or any)

One of the many reasons why Python is such a popular language is because it is readable and expressive.

Python之所以成为如此流行的语言的众多原因之一是因为它具有可读性和表现力。

It is often joked that Python is ‘executable pseudocode’. But when you can write code like this, it’s difficult to argue otherwise:

人们经常开玩笑说Python是“ 可执行伪代码 ”。 但是,当您可以像这样编写代码时,很难反驳:

x = [True, True, False]
if any(x):
    print("At least one True")
if all(x):
    print("Not one False")
if any(x) and not all(x):    
    print("At least one True and one False")

bashplotlib (bashplotlib)

You want to plot graphs in the console?

您要在控制台中绘制图形吗?

$ pip install bashplotlib

You can have graphs in the console.

您可以在控制台中使用图形。

馆藏 (collections)

Python has some great default datatypes, but sometimes they just won’t behave exactly how you’d like them to.

Python有一些很棒的默认数据类型,但有时它们只是无法完全按照您希望的方式运行。

Luckily, the Python Standard Library offers the collections module. This handy add-on provides you with further datatypes.

幸运的是,Python标准库提供了collections模块 。 这个方便的加载项为您提供了更多的数据类型。

from collections import OrderedDict, Counter

# Remembers the order the keys are added!
x = OrderedDict(a=1, b=2, c=3)

# Counts the frequency of each character
y = Counter("Hello World!")

目录 (dir)

Ever wondered how you can look inside a Python object and see what attributes it has? Of course you have.

有没有想过如何在Python对象内部查找并查看其具有的属性? 当然有

From the command line:

从命令行:

>>> dir()
>>> dir("Hello World")
>>> dir(dir)

This can be a really useful feature when running Python interactively, and for dynamically exploring objects and modules you are working with.

当以交互方式运行Python并动态浏览正在使用的对象和模块时,这可能是一个非常有用的功能。

Read more here.

在这里阅读更多。

表情符号 (emoji)

Yes, really.

是的, 真的 。

$ pip install emoji

Don’t pretend you’re not gonna try it out…

不要假装您不会尝试...

from emoji import emojize
print(emojize(":thumbs_up:"))

?

从__future__进口 (from __future__ import)

One consequence of Python’s popularity is that there are always new versions under development. New versions mean new features — unless your version is out-of-date.

Python受欢迎的一个后果是,总是有新版本正在开发中。 新版本意味着新功能-除非您的版本已过期。

Fear not, however. The __future__ module lets you import functionality from future versions of Python. It’s literally like time travel, or magic, or something.

但是不要害怕。 __future__模块可让您从将来的Python版本中导入功能。 从字面上看,这就像时光旅行,魔术一样。

from __future__ import print_function
print("Hello World!")

Why not have a go importing curly braces?

为什么不去导入花括号 ?

几何 (geopy)

Geography can be a challenging terrain for programmers to navigate (ha, a pun!). But the geopy module makes it unnervingly easy.

对于程序员来说,地理环境可能是一个充满挑战的领域(哈哈,双关语!)。 但是,geopy模块使其变得异常简单。

$ pip install geopy

It works by abstracting the APIs of a range of different geocoding services. It enables you to obtain a place’s full street address, latitude, longitude, and even altitude.

它通过抽象一系列不同地理编码服务的API来工作。 它使您能够获取地点的完整街道地址,纬度,经度,甚至高度。

There’s also a useful distance class. It calculates the distance between two locations in your favorite unit of measurement.

还有一个有用的距离课程。 它以您喜欢的度量单位计算两个位置之间的距离。

from geopy import GoogleV3

place = "221b Baker Street, London"
location = GoogleV3().geocode(place)
print(location.address)
print(location.location)

我如何 (howdoi)

Stuck on a coding problem and can’t remember that solution you saw before? Need to check StackOverflow, but don’t want to leave the terminal?

坚持编码问题,不记得您之前看到的解决方案吗? 需要检查StackOverflow,但不想离开终端吗?

Then you need this useful command line tool.

然后,您需要这个有用的命令行工具 。

$ pip install howdoi

Ask it whatever question you have, and it’ll do its best to return an answer.

询问任何问题,它都会尽力返回答案。

$ howdoi vertical align css
$ howdoi for loop in java
$ howdoi undo commits in git

Be aware though — it scrapes code from top answers from StackOverflow. It might not always give the most helpful information…

但是请注意,它会从StackOverflow的主要答案中抓取代码。 它可能不会总是提供最有用的信息…

$ howdoi exit vim

检查 (inspect)

Python’s inspect module is great for understanding what is happening behind the scenes. You can even call its methods on itself!

Python的inspect模块非常适合了解幕后发生的事情。 您甚至可以自己调用其方法!

The code sample below uses inspect.getsource() to print its own source code. It also uses inspect.getmodule() to print the module in which it was defined.

下面的代码示例使用inspect.getsource()打印自己的源代码。 它还使用inspect.getmodule()打印在其中定义模块的模块。

The last line of code prints out its own line number.

代码的最后一行打印出自己的行号。

import inspect

print(inspect.getsource(inspect.getsource))
print(inspect.getmodule(inspect.getmodule))
print(inspect.currentframe().f_lineno)

Of course, beyond these trivial uses, the inspect module can prove useful for understanding what your code is doing. You could also use it for writing self-documenting code.

当然,除了这些琐碎的用途外,检查模块对于证明您的代码在做什么也很有用。 您也可以使用它来编写自文档代码。

绝地 (Jedi)

The Jedi library is an autocompletion and code analysis library. It makes writing code quicker and more productive.

Jedi库是一个自动完成和代码分析库。 它使编写代码更快,更高效。

Unless you’re developing your own IDE, you’ll probably be most interested in using Jedi as an editor plugin. Luckily, there are already loads available!

除非您正在开发自己的IDE,否则您可能会对使用Jedi作为编辑器插件最感兴趣。 幸运的是,已经有负载可用!

You may already be using Jedi, however. The IPython project makes use of Jedi for its code autocompletion functionality.

但是,您可能已经在使用Jedi。 IPython项目将Jedi用于其代码自动完成功能。

**夸克 (**kwargs)

When learning any language, there are many milestones along the way. With Python, understanding the mysterious **kwargs syntax probably counts as one.

学习任何语言时,都有许多里程碑。 使用Python,了解神秘的**kwargs语法可能算作一个。

The double-asterisk in front of a dictionary object lets you pass the contents of that dictionary as named arguments to a function.

字典对象前面的双星号使您可以将该字典的内容作为命名参数传递给函数 。

The dictionary’s keys are the argument names, and the values are the values passed to the function. You don’t even need to call it kwargs!

字典的键是参数名称,值是传递给函数的值。 您甚至不需要称它为kwargs

dictionary = {"a": 1, "b": 2}

def someFunction(a, b):
    print(a + b)
    return
    
# these do the same thing:
someFunction(**dictionary)
someFunction(a=1, b=2)

This is useful when you want to write functions that can handle named arguments not defined in advance.

当您要编写可以处理事先未定义的命名参数的函数时,此功能很有用。

清单理解 (List comprehensions)

One of my favourite things about programming in Python are its list comprehensions.

关于Python编程我最喜欢的事情之一是它的列表理解 。

These expressions make it easy to write very clean code that reads almost like natural language.

这些表达式使编写非常干净的代码变得容易,该代码的读取方式几乎类似于自然语言。

You can read more about how to use them here.

您可以在此处阅读有关如何使用它们的更多信息。

numbers = [1,2,3,4,5,6,7]
evens = [x for x in numbers if x % 2 is 0]
odds = [y for y in numbers if y not in evens]

cities = ['London', 'Dublin', 'Oslo']

def visit(city):
    print("Welcome to "+city)
for city in cities:
    visit(city)

地图 (map)

Python supports functional programming through a number of inbuilt features. One of the most useful is the map() function — especially in combination with lambda functions.

Python通过许多内置功能支持函数式编程。 map()函数是最有用的函数之一,尤其是与lambda函数结合使用时。

x = [1, 2, 3]
y = map(lambda x : x + 1 , x)
# prints out [2,3,4]print(list(y))

In the example above, map() applies a simple lambda function to each element in x. It returns a map object, which can be converted to some iterable object such as a list or tuple.

在上面的示例中, map()将简单的lambda函数应用于x每个元素。 它返回一个映射对象,可以将其转换为一些可迭代的对象,例如列表或元组。

报纸3k (newspaper3k)

If you haven’t seen it already, then be prepared to have your mind blown by Python’s newspaper module.

如果您还没有看到它,那么请准备好让Python的报纸模块震惊 。

It lets you retrieve news articles and associated meta-data from a range of leading international publications. You can retrieve images, text and author names.

它使您可以从一系列领先的国际出版物中检索新闻文章和相关的元数据。 您可以检索图像,文本和作者名称。

It even has some inbuilt NLP functionality.

它甚至具有一些内置的NLP功能 。

So if you were thinking of using BeautifulSoup or some other DIY webscraping library for your next project, save yourself the time and effort and $ pip install newspaper3k instead.

因此,如果您正在考虑为下一个项目使用BeautifulSoup或其他DIY网站抓取库,则可以节省时间和精力,而$ pip install newspaper3k news3k。

运算符重载 (Operator overloading)

Python provides support for operator overloading, which is one of those terms that make you sound like a legit computer scientist.

Python提供了对运算符重载的支持,这是使您听起来像合法的计算机科学家的术语之一。

It’s actually a simple concept. Ever wondered why Python lets you use the + operator to add numbers and also to concatenate strings? That’s operator overloading in action.

这实际上是一个简单的概念。 有没有想过Python为什么让您使用+运算符来添加数字以及连接字符串? 这就是操作员超负荷运行。

You can define objects which use Python’s standard operator symbols in their own specific way. This lets you use them in contexts relevant to the objects you’re working with.

您可以定义使用Python的标准运算符以其特定方式使用的对象。 这使您可以在与要使用的对象相关的上下文中使用它们。

class Thing:
    def __init__(self, value):
        self.__value = value
    def __gt__(self, other):
        return self.__value > other.__value
    def __lt__(self, other):
        return self.__value < other.__value

something = Thing(100)
nothing = Thing(0)

# True
something > nothing

# False
something < nothing

# Error
something + nothing

pprint (pprint)

Python’s default print function does its job. But try printing out any large, nested object, and the result is rather ugly.

Python的默认print功能可以完成其工作。 但是,尝试打印出任何较大的嵌套对象,结果会很丑陋。

Here’s where the Standard Library’s pretty-print module steps in. This prints out complex structured objects in an easy-to-read format.

这是标准库的漂亮打印模块所处的位置。它以易于阅读的格式打印出复杂的结构化对象。

A must-have for any Python developer who works with non-trivial data structures.

任何使用非平凡数据结构的Python开发人员的必备工具。

import requests
import pprint

url = 'https://randomuser.me/api/?results=1'
users = requests.get(url).json()
pprint.pprint(users)

队列 (Queue)

Python supports multithreading, and this is facilitated by the Standard Library’s Queue module.

Python支持多线程,标准库的Queue模块促进了这一点。

This module lets you implement queue data structures. These are data structures that let you add and retrieve entries according to a specific rule.

该模块使您可以实现队列数据结构。 这些数据结构使您可以根据特定规则添加和检索条目。

‘First in, first out’ (or FIFO) queues let you retrieve objects in the order they were added. ‘Last in, first out’ (LIFO) queues let you access the most recently added objects first.

“先进先出”(或FIFO)队列使您可以按添加顺序检索对象。 “后进先出”(LIFO)队列使您可以首先访问最近添加的对象。

Finally, priority queues let you retrieve objects according to the order in which they are sorted.

最后,优先级队列使您可以根据对象的排序顺序检索对象。

Here’s an example of how to use queues for multithreaded programming in Python.

这是一个如何在Python中使用队列进行多线程编程的示例 。

__repr__ (__repr__)

When defining a class or an object in Python, it is useful to provide an ‘official’ way of representing that object as a string. For example:

在Python中定义类或对象时,提供一种“正式”的方式将该对象表示为字符串很有用。 例如:

>>> file = open('file.txt', 'r')
>>> print(file)

This makes debugging code a lot easier. Add it to your class definitions as below:

这使得调试代码容易得多。 将其添加到您的类定义中,如下所示:

class someClass:
    def __repr__(self):
        return ""
        
someInstance = someClass()

# prints 
print(someInstance)

SH (sh)

Python makes a great scripting language. Sometimes using the standard os and subprocess libraries can be a bit of a headache.

Python是一种很棒的脚本语言。 有时使用标准os和子流程库可能会让人有些头疼。

The sh library provides a neat alternative.

sh库提供了一种精巧的选择。

It lets you call any program as if it were an ordinary function — useful for automating workflows and tasks, all from within Python.

它使您可以像调用普通程序一样调用任何程序,这对从Python内部进行自动化工作流和任务很有用。

import sh
sh.pwd()
sh.mkdir('new_folder')
sh.touch('new_file.txt')
sh.whoami()
sh.echo('This is great!')

类型提示 (Type hints)

Python is a dynamically-typed language. You don’t need to specify datatypes when you define variables, functions, classes etc.

Python是一种动态类型的语言。 定义变量,函数,类等时,无需指定数据类型。

This allows for rapid development times. However, there are few things more annoying than a runtime error caused by a simple typing issue.

这样可以加快开发时间。 但是,除了简单的键入问题导致的运行时错误外,没有什么比这更令人讨厌了。

Since Python 3.5, you have the option to provide type hints when defining functions.

从Python 3.5开始 ,您可以选择在定义函数时提供类型提示。

def addTwo(x : Int) -> Int:    return x + 2

You can also define type aliases:

您还可以定义类型别名:

from typing import List
Vector = List[float]Matrix = List[Vector]
def addMatrix(a : Matrix, b : Matrix) -> Matrix:
    result = []
    for i,row in enumerate(a):
        result_row =[]
        for j, col in enumerate(row):
            result_row += [a[i][j] + b[i][j]]
        result += [result_row]
    return result

x = [[1.0, 0.0], [0.0, 1.0]]
y = [[2.0, 1.0], [0.0, -2.0]]
z = addMatrix(x, y)

Although not compulsory, type annotations can make your code easier to understand.

尽管不是强制性的,但类型注释可以使您的代码更易于理解。

They also allow you to use type checking tools to catch those stray TypeErrors before runtime. Probably worthwhile if you are working on large, complex projects!

它们还允许您使用类型检查工具在运行时捕获那些杂散的TypeError。 如果您正在从事大型,复杂的项目,则可能值得!

uid (uuid)

A quick and easy way to generate Universally Unique IDs (or ‘UUIDs’) is through the Python Standard Library’s uuid module.

生成通用唯一ID(或“ UUID”)的快速简便方法是通过Python标准库的uuid模块 。

import uuid

user_id = uuid.uuid4()
print(user_id)

This creates a randomized 128-bit number that will almost certainly be unique.

这将创建一个随机的128位数字,几乎可以肯定是唯一的。

In fact, there are over 2¹²² possible UUIDs that can be generated. That’s over five undecillion (or 5,000,000,000,000,000,000,000,000,000,000,000,000).

实际上,可以生成超过2 12²的UUID。 超过五十亿(或5,000,000,000,000,000,000,000,000,000,000,000,000,000,000)。

The probability of finding duplicates in a given set is extremely low. Even with a trillion UUIDs, the probability of a duplicate existing is much, much less than one-in-a-billion.

在给定集合中找到重复项的可能性非常低。 即使拥有一万亿个UUID,重复存在的可能性也远远小于十亿分之一。

Pretty good for two lines of code.

两行代码相当不错。

虚拟环境 (Virtual environments)

This is probably my favorite Python thing of all.

这可能是我最喜欢的Python。

Chances are you are working on multiple Python projects at any one time. Unfortunately, sometimes two projects will rely on different versions of the same dependency. Which do you install on your system?

您有可能同时从事多个Python项目。 不幸的是,有时两个项目将依赖于同一依赖项的不同版本。 您在系统上安装哪个?

Luckily, Python’s support for virtual environments lets you have the best of both worlds. From the command line:

幸运的是,Python 对虚拟环境的支持使您可以两全其美。 从命令行:

python -m venv my-project
source my-project/bin/activate
pip install all-the-modules

Now you can have standalone versions and installations of Python running on the same machine. Sorted!

现在,您可以在同一台计算机上运行Python的独立版本和安装。 排序!

维基百科 (wikipedia)

Wikipedia has a great API that allows users programmatic access to an unrivalled body of completely free knowledge and information.

维基百科具有出色的API,允许用户以编程方式访问无与伦比的完全免费的知识和信息。

The wikipedia module makes accessing this API almost embarrassingly convenient.

Wikipedia模块使访问此API变得非常尴尬。

import wikipedia

result = wikipedia.page('freeCodeCamp')
print(result.summary)

for link in result.links:
    print(link)

Like the real site, the module provides support for multiple languages, page disambiguation, random page retrieval, and even has a donate() method.

与实际站点一样,该模块提供了对多种语言,页面歧义消除,随机页面检索的支持,甚至还具有donate()方法。

xkcd (xkcd)

Humour is a key feature of the Python language — after all, it is named after the British comedy sketch show Monty Python’s Flying Circus. Much of Python’s official documentation references the show’s most famous sketches.

幽默是Python语言的一项主要功能-毕竟,它是以英国喜剧素描节目Monty Python的Flying Circus命名的 。 Python的许多官方文档都引用了展览中最著名的草图。

The sense of humour isn’t restricted to the docs, though. Have a go running the line below:

但是,幽默感不仅仅限于文档。 可以运行以下行:

import antigravity

Never change, Python. Never change.

永远不要改变,Python。 从不改变。

YAML (YAML)

YAML stands for ‘YAML Ain’t Markup Language’. It is a data formatting language, and is a superset of JSON.

YAML代表“ YAML不是标记语言 ”。 它是一种数据格式语言,并且是JSON的超集。

Unlike JSON, it can store more complex objects and refer to its own elements. You can also write comments, making it particularly suited to writing configuration files.

与JSON不同,它可以存储更复杂的对象并引用其自己的元素。 您还可以编写注释,使其特别适合编写配置文件。

The PyYAML module lets you use YAML with Python. Install with:

PyYAML模块允许您将YAML与Python一起使用。 安装方式:

$ pip install pyyaml

And then import into your projects:

然后导入到您的项目中:

import yaml

PyYAML lets you store Python objects of any datatype, and instances of any user-defined classes also.

PyYAML允许您存储任何数据类型的Python对象以及任何用户定义类的实例。

压缩 (zip)

One last trick for ya, and it really is a cool one. Ever needed to form a dictionary out of two lists?

ya的最后一招,这确实是很酷的。 是否曾经需要从两个列表中组成字典?

keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))

The zip() inbuilt function takes a number of iterable objects and returns a list of tuples. Each tuple groups the elements of the input objects by their positional index.

内置的zip()函数接受许多可迭代的对象,并返回一个元组列表。 每个元组通过其位置索引将输入对象的元素分组。

You can also ‘unzip’ objects by calling *zip() on them.

您也可以通过在对象上调用*zip()来“解压缩”对象。

谢谢阅读! (Thanks for reading!)

So there you have it, an A-Z of Python tricks — hopefully you’ve found something useful for your next project.

这样就构成了Python技巧的AZ-希望您已经找到了对下一个项目有用的东西。

Python’s a very diverse and well-developed language, so there’s bound to be many features I haven’t got round to including.

Python是一种非常多样化且开发完善的语言,因此肯定会有很多我没有想过的功能。

Please share any of your own favorite Python tricks by leaving a response below!

请在下面留下回复,分享您自己喜欢的任何Python技巧!

翻译自: https://www.freecodecamp.org/news/an-a-z-of-useful-python-tricks-b467524ee747/

python生成一系列数字

你可能感兴趣的:(数据结构,编程语言,python,java,人工智能)