Some tips for beginners in Python

Source: Internet
Author: User

Here are some of the python practical tips and tools I've collected in recent years that I hope will help you.


Swap variables


x = 6

y = 5

X, y = y, X

Print X

>>> 5

Print Y

>>> 6


If statement in row


Print "Hello" if True else "world"

>>> Hello


Connection


The last method below is cool when binding two different types of objects.


NFC = ["Packers", "49ers"]

AFC = ["Ravens", "patriots"]

Print NFC + AFC

>>> [' Packers ', ' 49ers ', ' Ravens ', ' patriots ']

Print str (1) + "World"

>>> 1 World

print ' 1 ' + "world"

>>> 1 World

Print 1, "World"

>>> 1 World

Print NFC, 1

>>> [' Packers ', ' 49ers '] 1


Digital tricks


#除后向下取整

Print 5.0//2

>>> 2

# 2 of the 5-time Square

Print 2**5

>> 32


Note the division of floating-point numbers


Print. 3/.1

>>> 2.9999999999999996

Print. 3//.1

>>> 2.0


Numerical comparison


This is one of the few simple methods I've seen in many languages.


x = 2

If 3 > x > 1:

Print X

>>> 2

If 1 < x > 0:

Print X

>>> 2


Iterate over two lists at a time


NFC = ["Packers", "49ers"]

AFC = ["Ravens", "patriots"]

For TeamA, teamb in Zip (NFC, AFC):

Print TeamA + "vs." + Teamb

>>> Packers vs. Ravens

>>> 49ers vs. Patriots


List Iteration with index


Teams = ["Packers", "49ers", "Ravens", "patriots"]

For index, team in enumerate (teams):

Print index, Team

>>> 0 Packers

>>> 1 49ers

>>> 2 Ravens

>>> 3 Patriots


List-derived


Given a list, we can swipe to select the even-numbered table method:


numbers = [1,2,3,4,5,6]

even = []

For number in numbers:

If number%2 = = 0:

Even.append (number)

Into the following:


numbers = [1,2,3,4,5,6]

even = [number for number in numbers if number%2 = = 0]

is not very cow, haha.


Dictionary derivation


Similar to list derivation, dictionaries can do the same thing:


Teams = ["Packers", "49ers", "Ravens", "patriots"]

Print {Key:value for value, key in enumerate (teams)}

>>> {' 49ers ': 1, ' Ravens ': 2, ' Patriots ': 3, ' Packers ': 0}


Initialize the value of the list


Items = [0]*3

Print items

>>> [0,0,0]


The list is converted to a string


Teams = ["Packers", "49ers", "Ravens", "patriots"]

Print ",". Join (teams)

>>> ' Packers, 49ers, Ravens, Patriots '


Get elements from a dictionary


I admit that the try/except code is not elegant, but there is an easy way to try to find the key in the dictionary, and if no corresponding alue is found, the second parameter will be set to its variable value.


data = {' user ': 1, ' name ': ' Max ', ' Three ': 4}

Try

Is_admin = data[' admin ']

Except Keyerror:

Is_admin = False


Replace with this:


data = {' user ': 1, ' name ': ' Max ', ' Three ': 4}

Is_admin = data.get (' admin ', False)


Get a subset of a list


Sometimes you just need some of the elements in the list, here are some ways to get a subset of the list.


x = [1,2,3,4,5,6]

#前3个

Print X[:3]

>>> [About]

#中间4个

Print X[1:5]

>>> [2,3,4,5]

#最后3个

Print X[-3:]

>>> [4,5,6]

#奇数项

Print X[::2]

>>> [1,3,5]

#偶数项

Print X[1::2]

>>> [2,4,6]


60 Character Resolution Fizzbuzz


A short time ago Jeff Atwood promoted a simple programming exercise called Fizzbuzz, which referred to the following questions:


Write a program that prints the number 1 to 100, 3 multiples print "Fizz" to replace this number, 5 multiples print "Buzz", for a number that is both a multiples of 3 and a multiples of 5 to print "Fizzbuzz".


Here is a short, interesting way to solve this problem:


For x in range (101):p rint "Fizz" [x%3*4::]+ "Buzz" [X%5*4::]or X


Collection


In addition to Python's built-in data types, the collection module also includes special use cases that are counter useful in some situations. If you've been in this year's Facebook Hackercup, you can even find out what's practical about him.


From collections Import Counter

Print Counter ("Hello")

>>> Counter ({' L ': 2, ' h ': 1, ' E ': 1, ' O ': 1})


Iterative Tools


As with the collections library, there is a library called Itertools, which can be effectively solved for some problems. One of the use cases is to find all the combinations that he can tell you about all the combinations of elements in a group


From Itertools import combinations

Teams = ["Packers", "49ers", "Ravens", "patriots"]

For-game in combinations (teams, 2):

Print game

>>> (' Packers ', ' 49ers ')

>>> (' Packers ', ' Ravens ')

>>> (' Packers ', ' patriots ')

>>> (' 49ers ', ' Ravens ')

>>> (' 49ers ', ' patriots ')

>>> (' Ravens ', ' patriots ')


False = = True


This is a very interesting thing compared to practical techniques, in Python, true and false are global variables, so:


False = True

If False:

Print "Hello"

Else

Print "World"

>>> Hello


This article from "Mr_computer" blog, reproduced please contact the author!

Some tips for beginners in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.