Python 数据类型
数据类型整理
类型 类型名称 说明 示例 对应Java类型 int 整数 整数 42、-7 byte, short, int, long float 浮点数 小数 3.14、-0.001 float, double bool 布尔 布尔 True 或 False boolean str 字符串 字符串 “hello”、“Python 3.9” char, String list 列表 可变序列 [1, 2, 3]、[“a”, “b”, “c”] Array tuple 元组 不可变序列 (1, 2, 3)、(“x”, “y”) Array dict 字典 键值对集合 {“name”: “Alice”, “age”: 30} Map set 集合 不重复元素集合 {1, 2, 3}、{“apple”, “banana”} Set NoneType 空类型 没有值或尚未初始化 None null
- int:整数
a = 42
b = - 7
print ( abs ( a) )
print ( pow ( a, 2 ) )
print ( max ( a, b) )
print ( min ( a, b) )
- float:浮点数
x = 3.14
y = - 0.001
z = 2.0
import math
print ( round ( x, 1 ) )
print ( math. sqrt( 16 ) )
print ( abs ( y) )
print ( max ( x, y, z) )
- bool:布尔
is_valid = True
is_active = False
print ( bool ( 1 ) )
print ( bool ( 0 ) )
print ( not is_valid)
- str:字符串
greeting = "hello"
name = "Python"
print ( len ( greeting) )
print ( greeting. upper( ) )
print ( greeting. lower( ) )
print ( greeting + " " + name)
print ( name. replace( "P" , "J" ) )
- list:列表
numbers = [ 1 , 2 , 3 , 4 , 5 ]
fruits = [ "apple" , "banana" , "cherry" ]
numbers. append( 6 )
print ( numbers)
fruits. remove( "banana" )
print ( fruits)
numbers. sort( )
print ( numbers)
print ( fruits[ 1 ] )
- tuple:元组
coordinates = ( 1 , 2 , 3 )
person = ( "Alice" , 30 , "Engineer" )
print ( coordinates[ 0 ] )
print ( person. count( "Alice" ) )
print ( person. index( 30 ) )
- dict:字典
person = { "name" : "Alice" , "age" : 30 , "city" : "New York" }
print ( person[ "name" ] )
person[ "age" ] = 31
print ( person)
person[ "job" ] = "Engineer"
print ( person)
print ( person. keys( ) )
print ( person. values( ) )
print ( person. get( "age" ) )
- set:集合
fruits = { "apple" , "banana" , "cherry" }
numbers = { 1 , 2 , 3 , 4 , 5 }
fruits. add( "orange" )
print ( fruits)
fruits. remove( "banana" )
print ( fruits)
numbers. discard( 3 )
print ( numbers)
union_set = fruits. union( { "pear" , "grape" } )
print ( union_set)
- NoneType:空类型
a = None
print ( type ( a) )