2

I am new to Python.

Start with: bins = [.05, .1, .2, 1.0, -.35, .07, .1].

How can I compress the following code into a single line in Python? It seems that it should be possible, but I get an error when I try it. Note: I do not want to define a multi-line function elsewhere and then apply it here - that is just hiding multiple lines of code under the hood.

bins_2 = [x for x in bins if x >= 0] # Retain only nonnegative reals.
bins_2.insert(0, 0.0) # Insert 0.0 to the beginning of the list
bins_2 = list(dict.fromkeys(bins_2)) # Dedup the list
bins_2.sort() # Sort bins into ascending order using the standard ordering of the integers

The output should be: bins_2 = [0.0, 0.05, 0.07, 0.1, 0.2, 1.0] .

It is not so much that I am opposed to having multiple lines of code (which can aid with clarity). However, I think that if I could figure out how to compress this code into a single line, then I would better understand what is happening with the related functions in the language in general. I also would like to be conscientious of run-time, so I would prefer to start with or append [0.0], read through bins and filter out negatives, deduplicate the list, and then sort it in the most-efficient order.


I think that the issue is related to the problem which underlies this question: Why does list.append() return None?

For the beginning, I tried: bins_2 = [0.0].extend([x for x in bins if x >= 0]).

I also tried:

bins_2 = (list(dict.fromkeys(bins.insert(0, 0.0)))).sort()
bins_2 = [x for x in bins_2 if x >= 0]

Both failed. I think that this is due to the fact that functions like insert() and sort() modify the list to which they are applied and therefore should not be saved to another (or the same-named) variable.

Hyperi
  • 23
  • 5

3 Answers3

2

If I understand you correctly you can do:

x = sorted(set(v for v in bins if v >= 0) | {0.0})
print(x)

Prints:

[0.0, 0.05, 0.07, 0.1, 0.2, 1.0]

For lower versions of python not supporting the union operator:

x = sorted(set(v for v in bins if v >= 0).union([0.0]))
print(x)
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
2

I would suggest using set instead of dictionary to dedup. You can combine it with list comprehension for filtering and the sort the result:

bins_2 = sorted(set([0.0] + [x for x in bins if x >= 0]))
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
1

You could use list concatenation [] + []:

result = sorted(list(dict.fromkeys([0.0] + [x for x in bins if x >= 0])))
Marcelo Paco
  • 2,732
  • 4
  • 9
  • 26