python如何替换列表的元素_【IT专家】python:用条件替换列表中的元素

本文由我司收集整编,推荐下载,如有疑问,请与我司联系

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

实现细节:除了数字之外的不同类型的对象按其类型名称排序

;

不支持正

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值