# 数据挖掘之Python基础（一）基本数据类型与数据结构

## 基本数据类型

### 数字

Python中将带小数点的数都当作浮点数处理，对于加减乘除的基本操作与其他语言没有什幺差别。

### 字符串

```poet = "We are all in the gutter, but some of us are looking for stars"
print(poet);```

```name = " Python"
name1 = " Python "
print(name.lstrip())
print(name1.strip())```

Python也是通过+来连接字符串

```name = "hello"+" Python"
print(name.lstrip())```

```age = 23
message = "Happy" + age + "rd Birthday"
print(message.lstrip())
# 报错
TypeError: can only concatenate str (not "int") to str
Traceback (most recent call last):
File "D:/Program Files/project/hello.py", line 3, in <module>
message = "Happy" + 23 + "rd Birthday"
TypeError: can only concatenate str (not "int") to str```

```age = 23
message = "Happy" + str(age) + "rd Birthday"
print(message.lstrip())```

### 列表

`names = ["Python", 'Java', 'C++']`

Python列表访问元素和修改元素与一些语言中的数据相类似，通过下标来访问和修改元素且下标从0开始。

`names[0] = 'go'`

`names.append('C')`

`names.insert(0, 'Ruby')`

list删除元素有很多种方法，可以使用del来删除元素。

`del names[0]`

`names.pop(0)`

`names.remove('Java')`

```nums = [1, 9, 7, 5, 4, 3, 2]
nums.sort(reverse=True)```

sort会永久改变列表，如果只是想临时排序可以使用sorted。

```nums = [1, 9, 7, 5, 4, 3, 2]
print(sorted(nums))```

```nums = [1, 9, 7, 5, 4, 3, 2]
nums.reverse()
print(nums)```

`len(nums)`

`nums[-1]`

```names = ["Python", 'Java', 'C++', 'go', 'Ruby']
for item in names:
print(item)```

```for i in range(1, 5, 2):
print(i)```

```nums = list(range(1, 5))
print(max(nums))
print(min(nums))
print(sum(nums))```

`squares = [value**2 for value in range(1, 5)]`

```squares = []
for value in range(1, 5):
squares.append(value**2)```

Python可以通过切片来获取列表的一部分。

```names = ["Python", 'Java', 'C++', 'go', 'Ruby']
print(names[1:3])
# 返回['Java', 'C++']```

[1:3]有点像以前数学的区间，右边是开区间，[1：3]就是【1，3）就是1，2。

### 元组

`names=('java', 'python')`

### 字典

```D = {}
D = {'egg': 1, 'ham': 2}```

`D ={'food': {'egg': 1, 'ham': 2}}`

```D = {'egg': 1, 'ham': 2}
print(D.keys())
print(D.values())
print(D.items())```

```D = {'egg': 1, 'ham': 2}
print(D.get('egg'))```

```D = {'egg': 1, 'ham': 2}
D['egg'] = 2
print(D)```

```D = {'egg': 1, 'ham': 2}
del D['egg']
D.pop('ham')```

```D1 = {'bread': 3}
D = {'egg': 1, 'ham': 2}
D.update(D1)
print(D)```

```D = {'egg': 1, 'ham': 2}
print(len(D))```