本文由我司收集整编,推荐下载,如有疑问,请与我司联系
python
:用条件替换列表中的元素
python
:用条件替换列表中的元素
[
英
]python:
replace
elements
in
list
with
conditional I am trying to do the following with python and am having a strange behavior.
Say I have the following list:
我正在尝试使用
python
执行以下操作并且我有一个奇怪的行为。说我有以下列
表:
x = [5, 4, 3, 2, 1] Now, I am doing something like:
现在,我正在做类似的事情:
x[x = 3] = 3 This gives:
这给出了:
x = [5, 3, 3, 2, 1] Why does only the second element get changed? I was expecting:
为什么只改变第二个元素?我在期待:
[3, 3, 3, 2, 1] 8
Because
Python
will
evaluated
the
x
=3
as
True
and
since
True
is
equal
to
1
so
the
second element of x will be converted to 3.
因为
Python
会将
x = 3
评估为
True
,因为
True
等于
1
因此
x
的第二个元素将转换
为
3
。
For such purpose you need to use a list comprehension :
为此,您需要使用列表理解:
[3
if
i
=3
else
i
for
i
in
x][3,
3,
3,
2,
1]
And
if
you
want
to
know
that
why
x
=
3
evaluates as True, see the following documentation :
如果您想知道为什么
x = 3
的计算结果为
True
,请参阅以下文档:
CPython
implementation
detail:
Objects
of
different
types
except
numbers
are
ordered
by
their
type
names;
objects
of
the
same
types
that
don
’
t
support
proper
comparison are ordered by their address.
CPython
实现细节:除了数字之外的不同类型的对象按其类型名称排序
;
不支持正