简体   繁体   English

为什么以下列表理解在Python中不起作用?

[英]Why is the following list comprehension not working in Python?

I have a list called row : 我有一个名为row的列表:

row = ['1234', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]]

I want to change row[1] , so that few numbers get replaced with a time and the rest gets replaced with the string 'ABS' . 我想更改row[1] ,以便少数数字被替换为时间,其余数字被替换为字符串'ABS' Something like this: 像这样的东西:

['1234', ['ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', '09:54:59', '09:55:18', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS', 'ABS']]

Here is my code: 这是我的代码:

for obj in row_objs:
    row[1] = [str(obj.punch.time()) if x==obj.punch.day else 'ABS' for x in row[1]]

But I keep getting ALL the numbers replaced by 'ABS' with the above code. 但我继续使用上面的代码将所有数字替换为'ABS'。

When I do this: 当我这样做:

for obj in row_objs:
    row[1] = [str(obj.punch.time()) if x==obj.punch.day else x for x in row[1]]

The time is placed correctly but the other numbers are still there. 时间安排正确,但其他数字仍然存在。

['1234', [1, 2, 3, 4, 5, 6, 7, '09:54:59', '09:55:18', 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]]

What is going wrong here? 这里出了什么问题?

You are replacing the list each iteration. 在每次迭代时替换列表。 The last obj in your for loop doesn't match any of the integers, so the end result is that you generated a list with only 'ABS' strings. for循环中的最后一个obj与任何整数都不匹配,因此最终结果是您生成的列表只包含'ABS'字符串。 Your second loop works because you take the already-replaced values by re-using x ; 您的第二个循环有效,因为您通过重新使用x来获取已经替换的值; that can be the original integer, or the later time() replacement. 可以是原始整数,也可以是更晚的time()替换。

Don't use a for loop. 不要使用for循环。 Collect all your obj.punch values in a dictionary mapping the day attribute to the str(...time()) result, then use a list comprehension to look up matches: 在将day属性映射到str(...time())结果的字典中收集所有obj.punch值,然后使用列表obj.punch来查找匹配:

days = {obj.punch.day: str(obj.punch.time()) for obj in row_objs}
row[1] = [days.get(x, 'ABS') for x in row[1]]

Now you replace row[1] just once. 现在你只需将row[1]替换一次。

for obj in row_objs:
    row[1] = [str(obj.punch.time()) if x == obj.punch.day else isinstance(x, int) and 'ABS' or x for x in row[1]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM