美文网首页
python基本数据类型

python基本数据类型

作者: esskeetit | 来源:发表于2018-05-25 11:17 被阅读0次

math

print(math.floor(98.6))  #向下取整
print(math.ceil(98.6)) #向上取整
print(math.pow(2, 3)) #math.pow always return a float.
print(2**3)
math.sqrt(25)

Extract &Slice

letters = "abcdefghijklmnopqrstuvwxyz"
letters[-1]   #取最后一个字母
letters = "abcdefghijklmnopqrstuvwxyz"
letters[1:5:2]   #步长为2,表示隔一个取
letters[::-1] #返回字符串的逆序

Split & Combine

lan = "python ruby c c++ swift"
lan.split()   #默认分隔符为空格

todos = "download python, install, download ide, learn"
todos.split(',')
todos.split(',',maxsplit=-1)#maxsplit表示分割几次结束,默认-1,表示全部分割完

'自定义分隔符'.join(['download python', 'install', 'download ide', 'learn'])

Substitue

s = 'I like C. I like C++. I like Python'
s.replace('like', 'hate',1)   #1为替换次数

Other useful tools

py_desc = "Python description: Python is a programming language that lets you work quickly and integrate systems more effectively."
py_desc.startswith('Python')
py_desc.endswith('effectively.')
py_desc.find('language') #找第一个
py_desc.count("Python") #句子中单词出现的次数
py_desc.strip('.') #去掉首尾的'.'
py_desc.upper() #全部大写
py_desc.title()#首字母大写
age=input("how old are you?\n")
height = input('how tall are you?\n')
weight = input('how heavy are you?\n ')
print (f"so you are {age} years old, {weight} kg heavy and {height}meters tall")

in and out

### Read user input ###
age = input("How old are you?")
height = input("How tall are you?")
weight = input("How much do you weigh?")
print("So, you're %s old, %s tall and %s heavy." % (age, height, weight))
print('%s %s' % ('one', 'two'))
print('{} {}'.format('one', 'two'))
print('%d %d' % (1, 2))
print('{} {}'.format(1, 2))

字符串格式输出

print('%s %s' % ('one', 'two'))
print('{} {}'.format('one', 'two'))
print('%d %d' % (1, 2))
print('{} {}'.format(1, 2))

a = 5
b = 10
print(f'Five plus ten is {a + b} and not {2 * (a + b)}.')
print('{first} {second}'.format(first='one', second='two'))

container types

  1. List
  2. Tuple
  3. Dictionary
  4. Set

list

weekdays = ['Monday','Tuesday','Wednesday','Thursday','Friday']
del weekdays[0]  #永久删除
print(weekdays)

weekdays.remove('Tuesday')#永久删除
print(weekdays)

print('Tuesday' in weekdays)  #False

weekdays = ['Monday','Tuesday','Wednesday','Thursday','Friday']
weekdays.append('Friday')  #在列表末尾添加
print(weekdays)

weekdays.insert(0, 'Monday') #在特定位置插入
print(weekdays)

#pop
weekdays = ['Monday','Tuesday','Wednesday','Thursday','Friday']
last_day = weekdays.pop() #pop()函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
print("last_day = ", last_day, "\nweekdays = ", weekdays)
print (weekdays)

weekdays = ['Monday','Tuesday','Wednesday','Thursday','Friday']
first_day = weekdays.pop(0)
print("first_day = ", first_day, "\nweekdays = ", weekdays)

nums = [1,4,2,5,3]
sorted_nums = sorted(nums)  #The general function sorted() returns a sorted copy of the list.
print("nums =", nums, "\nsorted_nums =", sorted_nums)

nums.sort()#The list method sort() sorts the list itself, in place.
nums

nums.sort(reverse=True)
nums

#assign vs copy
a = [1,2,3]
b = a
print("a = ", a, "\nb = ", b)

a[0] = 2
print("a = ", a, "\nb = ", b)


a = [1,2,3]
b = a
c = a.copy() #c/d/仍是原来的a
d = a[:]
e = list(a)

a[0] = 2
print("a = ", a, "\nb = ", b, "\nc = ", c, "\nd = ", d, "\ne = ", e)#c/d/仍是原来的a

Tuple

Similar to lists, tuples are also sequences of arbitrary items. However, tuples are immutable. You can not add, detele or change it after it is defined.

dict

dict.keys()
dict.values()
dict.items()
dict[key_1]=['value_1','value_2']  #修改字典的值
del dict[key_1]  #删除键值对

set

empty_set = set()
empty_set

even_set = {2,4,6,6,8,10}   #元素都是唯一的
even_set

even_set = {2,4,6,6,8,10}
num_set = {3,6,9,12,15,18}
num_set & even_set
num_set | even_set
num_set - even_set
even_set ^ num_set   # 对称差集(项在t或s中,但不会同时出现在二者中)

Convert into List

print(list('ababc'))
print(list((1,2,3,4)))
print(list({'name': 'Ed', 'employer': 'Oracle'}))
print(list({'name': 'Ed', 'employer': 'Oracle'}.values()))
print(list({5,6,7,8}))

Convert into Dictionary

dict(['ab', 'cd', 'ef']) #{'a': 'b', 'c': 'd', 'e': 'f'}
dict([['a', 'b'], ('c', 'd'), ('e', 'f')]) #{'a': 'b', 'c': 'd', 'e': 'f'}

s1 = 'abcdefg'
s2 = 'hijklmn'
list(zip(s1, s2))   #zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

s3, s4 = zip(*d)
print(list(s3))
print(list(s4))
Mutable, Immutable
image.png

遍历

for key,day in enumerate(weekdays):
    print(str(key)+" "+day)

List Comprehension

#Format: `[expression for item in iterable]`
num_list = [i for i in range(0, 10)]
print(num_list)

# format [expression for item in iterable if condition]
num_list = [i for i in range(0,10) if i % 2 == 1]  #%是取余,//是取整
print(num_list)

相关文章

网友评论

      本文标题:python基本数据类型

      本文链接:https://www.haomeiwen.com/subject/fwfejftx.html