Some programming tips for a Python beginner _python

Source: Internet
Author: User
Exchange 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 looks 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 skills

#除后向下取整
Print 5.0//2
>>> 2
# 2 of the 5
2**5 page
>> 32

Note The division of floating-point numbers

Print. 3/.1
>>> 2.9999999999999996
print. 3//.1
>>> 2.0

Numerical comparison

It's the easiest way I've ever seen a lot of languages.

x = 2
If 3 > x > 1:
 print x
>>> 2
if 1 < x > 0:
 print x
>>> 2

Iterate two lists at the same 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 iterations with indexes

Teams = ["Packers", "49ers", "Ravens", "patriots"] for
index, team in enumerate (teams):
 Print index, Team
;>> 0 Packers
>>> 1 49ers
>>> 2 Ravens
>>> 3 Patriots

List inference Type

Given a list, we can brush the selection of the even number list method:

numbers = [1,2,3,4,5,6]
even = [] for number in
numbers:
 If number%2 = 0:
  even.append (number)

Turned 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 job:

Teams = ["Packers", "49ers", "Ravens", "patriots"]
print {Key:value for value, key in enumerate (teams)}
>>& Gt {' 49ers ': 1, ' Ravens ': 2, ' Patriots ': 3, ' Packers ': 0}

Initialize the value of a list

Items = [0]*3
print Items
>>> [0,0,0]

Convert List to String

Teams = ["Packers", "49ers", "Ravens", "patriots"]
print ",". Join (teams)
>>> ' Packers, 49ers, Ravens , Patriots '

Get elements from the dictionary

I admit try/except code is not elegant, but here is a simple way to try to find the key in the dictionary, if you do not find the corresponding alue will be set with the second parameter to its variable value.

data = {' user ': 1, ' name ': ' Max ', ' Three ': 4}
try:
 is_admin = data[' admin ']
except keyerror:
 is_ admin = False
1
 

Replace sincerity like 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, and here are some ways to get a subset of the list.

x = [1,2,3,4,5,6]
#前3个
print X[:3]
>>> [1,2,3]
#中间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 characters to solve Fizzbuzz

Some time ago Jeff Atwood promoted a simple programming exercise called Fizzbuzz, citing the following questions:

Write a program that prints numbers 1 to 100, multiples of 3, prints "fizz" to replace this number, 5 multiples print "Buzz", and Prints "fizzbuzz" for numbers that are multiples of 3 and 5.

Here's a short, interesting way to solve this problem:

For x in range (: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, which in some cases counter very practical. If you've been in a Facebook Hackercup this year, you can even find out what he's practical about.

From collections import Counter
print Counter ("Hello")
>>> Counter ({' L ': 2, ' h ': 1, ' E ': 1, ' O ': 1})

Iteration Tools

As with the collections library, there is also a library called Itertools, which can effectively solve some problems. One of the use cases is to look up all the combinations, and he can tell you all the possible combinations of elements in a group

From Itertools import combinations
teams = ["Packers", "49ers", "Ravens", "patriots"] for
game in combinations (Te AMS, 2:
 print game
>>> (' Packers ', ' 49ers ')
>>> (' Packers ', ' Ravens ')
>> > (' Packers ', ' patriots ')
>>> (' 49ers ', ' Ravens ')
>>> (' 49ers ', ' Patriots ')
> >> (' Ravens ', ' patriots ')

False = = True

It's a lot more interesting than practical technology, in Python, true and false are global variables, so:

false = True
If false:
 print "Hello"
else:
 print "World"
>>> Hello

Related Article

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.