简体   繁体   中英

Why is the following list comprehension not working in Python?

I have a list called 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' . 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.

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. Your second loop works because you take the already-replaced values by re-using x ; that can be the original integer, or the later time() replacement.

Don't use a for loop. 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:

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.

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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