如何进行列表理解中的作业? [英] How can I do assignments in a list comprehension?

查看:52
本文介绍了如何进行列表理解中的作业?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在列表理解中使用赋值运算符.我该怎么办?

I want to use the assignment operator in a list comprehension. How can I do that?

以下代码是无效的语法.我的意思是将lst[0]设置为与pattern匹配的空字符串'':

The following code is invalid syntax. I mean to set lst[0] to an empty string '' if it matches pattern:

[ lst[0] = '' for pattern in start_pattern if lst[0] == pattern ]

谢谢!

推荐答案

您似乎对循环构造的"noreferrer>列表理解.

It looks like you are confusing list comprehension with looping constructs in Python.

产生列表理解-列表!它不会将自己分配给现有列表中的单个分配. (尽管您可以折磨语法来做到这一点...)

A list comprehension produces -- a list! It does not lend itself to a single assignment in an existing list. (Although you can torture the syntax to do that...)

虽然不清楚您要从代码中执行什么操作,但我认为它更类似于遍历列表(流控制)而不是生成列表(列表理解)

While it isn't exactly clear what you are trying to do from your code, I think it is more similar to looping over the list (flow control) vs producing a list (list comprehension)

像这样遍历列表:

for pattern in patterns:
   if lst[0] == pattern: lst[0]=''

这是执行此操作的一种合理方法,也是您在C,Pascal等环境中要做的事情.但是您也可以只测试列表中的一个值并对其进行更改:

That is a reasonable way to do this, and is what you would do in C, Pascal, etc. But you can also just test the list for the one value and change it:

if lst[0] in patterns: lst[0] = ''

或者,如果您不知道索引:

Or, if you don't know the index:

i=lst.index[pattern]
lst[i]=''

或者,如果您有一个列表列表,并且想要更改每个子列表的每个第一个元素:

or, if you have a list of lists and want to change each first element of each sublist:

for i, sublst in enumerate(lst):
    if sublst[i][0] in patterns: sublist[i][0]=''

等,等等

如果要对列表的每个元素应用某些内容,则可以使用列表推导,映射或Python套件中的许多其他工具之一进行查看.

If you want to apply something to each element of a list, then you can look at using a list comprehension, or map, or one of the many other tools in the Python kit.

就个人而言,我通常倾向于更多地使用列表理解来创建列表:

Personally, I usually tend to use list comprehensions more for list creation:

 l=[[ x for x in range(5) ] for y in range(4)]  #init a list of lists...

比以下哪个更自然?

l=[]
for i in range(4):
   l.append([])
   for j in range(5):
      l[i].append(j)      

但是要修改相同的列表列表,这更容易理解吗?

But to modify that same list of lists, which is more understandable?

此:

l=[['new value' if j==0 else l[i][j] for j in range(len(l[i]))] for i in range(len(l))]

或者这个:

for i,outter in enumerate(l):
    l[i][0]='new value'               

YMMV

此处是一个很棒的教程.

这篇关于如何进行列表理解中的作业?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆