多语言展示
当前在线:1627今日阅读:23今日分享:25

python 基础数据结构简介

python是一种非常强大的编程语言,他在数据科学领域是一款非常强大的工具。下面我将介绍一下python 中非常基本的数据类型的使用,包括整型,浮点型,布尔类型,字符串等。
工具/原料
1

python 3.7

2

IDE: Spyder

方法/步骤
1

整型和浮点型的基本用法与其他语言的使用方法是一样的。基本用法:x = 3print(type(x)) # Prints ''print(x)       # Prints '3'print(x + 1)   # Addition; prints '4'print(x - 1)   # Subtraction; prints '2'print(x * 2)   # Multiplication; prints '6'print(x**2)  # Exponentiation; prints '9'x += 1print(x)  # Prints '4'x *= 2print(x)  # Prints '8'y = 2.5print(type(y)) # Prints ''print(y, y + 1, y * 2, y ** 2) # Prints '2.5 3.5 5.0 6.25'

2

上述程序的而运行结果如下:34269482.5 3.5 5.0 6.25

3

Booleans: python 常常使用英文字母来实现逻辑运算,而不是使用操作符&&,||等。使用详解:t = Truef = Falseprint(type(t)) # Prints ''print(t and f) # Logical AND; prints 'False'print(t or f)  # Logical OR; prints 'True'print(not t)   # Logical NOT; prints 'False'print(t != f)  # Logical XOR; prints 'True'

4

步骤三程序的运行结果如下所示:FalseTrueFalseTrue

5

Python支持字符串类型的操作。使用如下:hello = 'hello'    # String literals can use single quotesworld = 'world'    # or double quotes; it does not matter.print(hello)       # Prints 'hello'print(len(hello))  # String length; prints '5'hw = hello + ' ' + world  # String concatenationprint(hw)  # prints 'hello world'hw12 = '%s %s %d' % (hello, world, 12)  # sprintf style string formattingprint(hw12)  # prints 'hello world 12'

6

运行结果:hello5hello worldhello world 12

7

string拥有这许多有用的方法。如下:s = 'hello'print(s.capitalize())  # Capitalize a string; prints 'Hello'print(s.upper())       # Convert a string to uppercase; prints 'HELLO'print(s.rjust(7))      # Right-justify a string, padding with spaces; prints '  hello'print(s.center(7))     # Center a string, padding with spaces; prints ' hello 'print(s.replace('l', '(ell)'))  # Replace all instances of one substring with another;                                # prints 'he(ell)(ell)o'print('  world '.strip())  # Strip leading and trailing whitespace; prints 'world'

8

运行结果如下:HelloHELLO  hello hello he(ell)(ell)oworld

推荐信息