加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

【Python有坑系列大合集】

发布时间:2020-05-27 04:45:17 所属栏目:Python 来源:互联网
导读:Anaconda安装踩过的坑:python中安装yaml时,应该安装pyyaml:condainstallpyyaml创建新环境:condacreate-nnamepython=3.6.3

Anaconda安装踩过的坑:

python中安装yaml时,应该安装pyyaml:conda install pyyaml
创建新环境:conda create -n name python=3.6.3
安装失败,提示channel不符合。
解决:
输入命令: conda update conda ”。
然后输入以下命令:conda create -n py363 python=3.6.3 anaconda ”。

成功,随后可以activate py363。

关于错误:ImportError: No module named yaml,注意:

pip install pyyaml lets you import yaml. This package enables Python to parse YAML files.
pip install pyaml lets you import pyaml. This package allows pretty-printing of YAML files

======================================

坑1:一边遍历,一边删除列表元素

可能出现问题:下标超出范围报错,或者返回结果不正确。

<pre class="has">
<code class="language-python">a=[1,2,3,4,5,6,7]
b=[1,6]
for it in a:
if it not in b:
print("remove ",it)
print(a)
a.remove(it)
print(a)
remove 2
[1,7]
[1,7]
remove 4
[1,7]
remove 7
[1,6]

坑2:b=a,修改a,结果b也被改变了。

坑3:input输入一个数字,使用时发现变成了字符串。

如果想使用input()函数输入一个数值,在得到结果后需要用int()将字符串类型转换为数值类型。

坑4:在for循环体内改变循环变量的值,结果下次循环依然不被影响。

<pre class="has">
<code class="language-python">for i in range(3):
print "original:",i
i=i+3
print "new",i

original: 0
new 3
original: 1
new 4
original: 2
new 5

典型的用C语言思想,python并不买账。

<pre class="has">
<code class="language-python">>>> a=[1,1]

a.remove(a[-1])
a
[2,1]

如上代码,本来是想删除最后一个元素,结果误删第一个。

而对于 del 来说,它是根据索引(元素所在位置)来删除的,如下例:

<pre class="has">
<code class="language-python">>>> a=[1,1]

del a[0]
a
[2,1]

pop是根据索引,返回的是索引指向那个数值。

<pre class="has">
<code class="language-python">>>> a=[1,1]

a.pop(2)
3

坑6:python中字典的items()函数返回类型为list

我们知道两个列表可直接相加,两个字典直接相加会报错。

于是想到一种相加方式:a.items()+b.items()。但是错误地得到了一个列表。

<pre class="has">
<code class="language-python">>>> a={1:2}

b={3:4}
a+b
Traceback (most recent call last):
File "<pyshell#123>",line 1,in
a+b
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

c=a.items()+b.items()
c
[(1,2),(3,4)]
type(c)
<type 'list'>

<pre class="has">
<code class="language-html">正确使用方式:update()

<pre class="has">
<code class="language-python">>>> a
{1: 2}

b
{3: 4}
a.update(b)
a
{1: 2,3: 4}

<pre class="has">
<code class="language-python">>>> a=(1,2)

(a)
(1,2)
b=[1,2]
(b)
[1,2]
tuple(a)
(1,2)
tuple(b)
(1,2)
tuple([a])
((1,)

这告诉我们如果需要使用元祖,最好用tuple()函数转换,而不是加括号强制转化。

<pre class="has">
<code class="language-python">>>> a=["1t4","atb"]

for item in a:
item = item.split("t")

a
['1t4','atb']

for i in range(len(a)):
a[i]=a[i].split("t")

a
[['1','4'],['a','b']]

列表解析总共有两种形式,很容易把二者混淆:

1. [i for i in range(k) if condition]:此时if起条件判断作用,满足条件的,将被返回成为最终生成的列表的一员。

2. [i if condition else exp for exp]:此时if...else被用来赋值,满足条件的i以及else被用来生成最终的列表。

以上情况对多个for仍然成立。

<pre class="has">
<code class="language-python">print([i for i in range(10) if i%2 == 0])
print([i if i == 0 else 100 for i in range(10)])

[0,8]
[0,100,100]

坑10:矩阵转变为数组,再求和

<pre class="has">
<code class="language-python">>>> a=np.mat([[1,3],[4,6]])

a
matrix([[1,6]])
sum(a)
matrix([[5,7,9]])
b=[[1,6]]
sum(b)
Traceback (most recent call last):
File "",in
TypeError: unsupported operand type(s) for +: 'int' and 'list'
np.array(a)
array([[1,6]])
np.array(sum(a))
array([[5,9]])
np.array(sum(a))[0]
array([5,9])
np.array(sum(a)[0])
array([[5,9]])

坑11:float精度损失、round假四舍五入

<pre class="has">
<code class="language-python">>>> b=max(np.linalg.eigvals(a))

b
5.3722813232690143
round(b,3)
5.3719999999999999
round(b,2)
5.3700000000000001

可以看到两个问题:一室无限循环;二是精度损失;

建议不要用round(),因为它不是严格意义上的四舍五入,而是遇到5舍入时接近一个偶数;

建议用格式化表示:

<pre class="has">
<code class="language-python">>>> c = "%.4f" % b

c
'5.3723'
float(c)
5.3723

坑12:对象赋值,实际传递了引用

定义类:

<pre class="has">
<code class="language-python">import numpy as np
class ModelParams(object):
def init(self):
self.beta = 0.8*np.ones(NUMBER_OF_NODES)

定义对象p,并赋值给p1:

<pre class="has">
<code class="language-python">p = NodeParams()
print(">>>>test<<<<")
print(p.beta)
p1 = p
p1.beta = -1*np.ones(len(p.beta))
print(p.beta)
print(p1.beta)

结果(错误):

<pre class="has">
<code class="language-python">>>>>test<<<<
[ 0.8 0.8 0.8 0.8 0.8]
[-1. -1. -1. -1. -1.]
[-1. -1. -1. -1. -1.]

可以看到,对象的赋值只是传递了一个引用,改变被赋值的对象,原对象也会被改变。解决:采用深拷贝进行赋值

<pre class="has">
<code class="language-python">from copy import deepcopy

p = NodeParams()
print(">>>>test<<<<")
print(p.beta)
p1 = p
p1.beta = -1*np.ones(len(p.beta))
print(p.beta)
print(p1.beta)

结果(正确):

<pre class="has">
<code class="language-python">>>>>test<<<<
[ 0.8 0.8 0.8 0.8 0.8]
[ 0.8 0.8 0.8 0.8 0.8]
[-1. -1. -1. -1. -1.]
123

坑12:列表相加与numpy数组相加

<pre class="has">
<code class="language-python">a=[1,3]

b=[4,6]

a+b
Out[447]: [1,6]

a=np.array(a)

b=np.array(b)

a,b
Out[450]: (array([1,3]),array([4,6]))

a+b
Out[451]: array([5,9])

解决:用 numpy.concatenate 拼接多个数组

坑13:矩阵相乘与数组相乘

<pre class="has">
<code class="language-python">a=[[0,1],[2,3]]
c1=np.array(a)
c2=np.array([1,2])
c2*c1
Out[119]:
array([[0,2],6]])

np.mat(c2)*np.mat(c1)
Out[120]: matrix([[4,7]])

坑14:格式化打印矩阵与打印数组

打印矩阵(失败):

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读