previous answers on how to remove None from a list dont help me!
I am creating a list of tuples with:
list(zip(*[iter(pointList)] *3))
So what i have is
[(object1,object2,object3),(object4,object5,object6),(object7,None,None)]
or
[(object1,object2,object3),(object4,object5,object6),(object7,object8,None)]
And i want to remove the None in the tuples (which only can occure at the last entry of the list!). So my desired output would be:
[(object1,object2,object3),(object4,object5,object6),(object7)]
or
[(object1,object2,object3),(object4,object5,object6),(object7,object8)]
What i thought would help me is:
filter(None,myList)
Tuples are immutable so once you construct a tuple you cannot alter its length or set its elements. Your only option is thus to construct new tuples as a post processing step, or don't generate these tuples in the first place.
Post processing
Simply use a generator with the tuple(..) constructor in a list comprehension statement:
[tuple(xi for xi in x if xi is not None) for x in data]
Alter the "packing" algorithm
With packing I mean converting a list of m×n items into n "slices" of m elements (which is what your first code fragment does).
If - like the variable name seems to suggest - pointList is a list. You can save yourself the trouble of using zip, and work with:
[tuple(pointList[i:i+3]) for i in range(0,len(pointList),3)]
directly. This will probably be a bit more efficient as well since here we never generate tuples with Nones in the first place (given postList does not contain Nones of course).
Related
for example I have a list of list of integers like
x = [[1,2,3,4], [4,5,6], [2,3,1,9]]
Assume the length of x is in million. In that case iterating trough each element will be very slow.
Is there any faster way?
Without any prior knowledge or extra information about the list (e.g., whether its sorted), you have no real choice but to iterate over the entire list. Note, however, that doing this with a generator could be must more performant than creating a filtered list, as the values are calculated just when you attempt to consume them, and not upfront:
search = 2
listGenerator = (i for i in x if search in i)
I would like to extract more than 1 pair of tuples in even or odd positions. For example the first and the last. I have read many questions and all of them are referring to how to extract a specific one from each tuple, but I have to have 2 pairs.
I am using for example test2 (already made as tuple) and currently trying to figure it out with:
Tuplewanted=[x[0::1] for x in Tuple]
Tuplewanted
Out[44]:
[(778933.8147968281, 5803816.850292235),
(778999.2820487045, 5804014.491034968),
(779011.4321377204, 5804048.532974694),
(779024.8198435705, 5804081.474176192),
(779039.3061023126, 5804115.648560766),
(779055.1628175485, 5804146.376816435),
(779072.6698779828, 5804178.971719031),
(779121.9406760866, 5804267.038294602)]
while I want only the 1st tuple and the last
Tuplewanted= [(778933.8147968281, 5803816.850292235),(779121.9406760866, 5804267.038294602)]
Anyone?
Note that Typewanted[0] and Typewanted[7] and the .append cannot work since I have a list with more than 100000 of those tuple lists.
Solution
Tuplewanted['coords']=[ix.coords[::len(ix.coords)-1]for ix in Tuple.geometry]
Thank you again
I am not quite sure what you want exactly. If you just want the last tuple, you can do this :list[-1]
Caveat: this is a straight up question for code-golfing, so I know what I'm asking is bad practise in production
I'm trying to alter an array during a list comprehension, but for some reason it is hanging and I don't know why or how to fix this.
I'm dealing with a list of lists of indeterminite depth and need to condense them to a flat list - for those curious its this question. But at this stage, lets just say I need a flat list of all the elements in the list, and 0 if it is a list.
The normal method is to iterate through the list and if its a list add it to the end, like so:
for o in x:
if type(o)==type([]):x+=o
else:i+=o
print i
I'm trying to shorten this using list comprehension, like so.
print sum([
[o,x.append(o) or 0][type(o)==type([])]
for o in x
]))
Now, I know List.append returns None, so to ensure that I get a numeric value, lazy evaluation says I can do x.append(o) or 0, and since None is "falsy" it will evaulate the second part and the value is 0.
But it doesn't. If I put x.append() into the list comprehension over x, it doesn't break or error, or return an iteration error, it just freezes. Why does append freeze during the list comprehension, but the for loop above works fine?
edit: To keep this question from being deleted, I'm not looking for golfing tips (they are very educational though), I was looking for an answer as to why the code wasn't working as I had written it.
or may be lazy, but list definitions aren't. For each o in x, when the [o,x.append(o) or 0][type(o)==type([])] monstrosity is evaluated, Python has to evaluate [o,x.append(o) or 0], which means evaluating x.append(o) or 0, which means that o will be appended to x regardless of whether it's a list. Thus, you end up with every element of x appended to x, and then they get appended again and again and again and OutOfMemoryError
What about:
y = [element for element in x if type(element) != list or x.extend(element)]
(note that extend will flatten, while append will only add the nested list back to the end, unflattened).
Please help me understand the following code snippet :-
def any(l):
"whether any number is known from list l"
s = set(list(l)[0])
for x in l:
s.intersection_update(set(x))
return len(s) > 0
Here l is a list containing the list of 3-tuples e.g [(17,14,13),(19,17,2),(22,11,7),(22,13,1),(23,10,5),(23,11,2),(25,5,2)] etc.
In particular I am facing difficulty understanding the line 3
s=set(list(l)[0])
set(list(l)[0])
list(l) creates a new list from land then [0] is to fetch its first item, which is (17,14,13).
and then set((17,14,13)) returns a set of this tuple.
set is a data structure which contains only unique hash-able elements.
i.e set((10,12,10)) equals {10,12}
>>> l=[(17,14,13),(19,17,2),(22,11,7),(22,13,1),(23,10,5),(23,11,2),(25,5,2)]
>>> list(l)[0]
(17, 14, 13)
>>> set(list(l)[0])
{17, 13, 14}
In s=set(list(l)[0]), you're creating a set from the first element of the list. In your case, you could have used set(l[0]) and it would do the same thing. Essentially, you're creating a set based on the first tuple of the list. Overall, your function is trying to find if there is any common element(number) between all tuples.
A set is a python collection of hashable-types that has the special feature that no entity in the collection can repeat (the hash returned from it's __hash__ magic method, and thereby also the boolean return from the __eq__ method cannot be equal to any other entity in the list) It is used wherever a collection is required that can not have repeated entities.
It's hard to tell the intention of the snippet entirely without knowing the context of its use, especially since the values you have for l are all tuples within a container list. The intersection_update is a method of a set that returns a set from the original keeping only elements also found in the one that is passed as an argument. The zero-indexed key is fetching the first tuple from the list.
http://docs.python.org/library/sets.html
I've started teaching myself Python, and as an exercise I've set myself the task of generating lookup tables I need for another project.
I need to generate a list of 256 elements in which each element is the value of math.sin(2*i*pi/256). The problem is, I don't know how to generate a list initialized to "dummy" values that I can then use a for loop to step through and assign the values of the sin function.
Using list() seems to create an "empty" list, but with no elements so I get a "list assignment index out of range" error in the loop. Is there a way to this other than explicitly creating a list declaration containing 256 elements all with "0" as a value?
Two answers have already shown you how to build your list at a single stroke, using the "list comprehension" (AKA "listcomp") construct.
To answer your specific question, though,
mylist = [None] * 256
is the simplest way to make a list with 256 items, all None, in case you want to fill it in later.
If you start with an empty list, call its .append(...) method to add each item at the end. A loop doing nothing but append on an initially-empty list is what normally gets replaced with a more concise listcomp.
Of course, for the task you actually state,
mylist = [math.sin(2 * math.pi/256)] * 256
would be by far the best approach -- no sense computing a sin 256 times when the argument's always the same (daringly assuming that what you say is what you mean;-).
my_list = [math.sin(2 * math.pi/256) for i in xrange(256)]
You can also try:
l = []
for i in range(256):
l.append(math.sin(2*math.pi/256))
This is an iterative for loop that keeps adding the same value to the end of the list 256 times
I need to generate a list of 256
elements in which each element is the
value of math.sin(2*math.pi/256)
To answer your question literally:
my_list=[math.sin(2*math.pi/256)]*256
Thanks for the help, everyone. I did make a mistake in the specification I posted for the question, in that the value of each element in the list needs to be the sin of the angle incremented by 2*pi/256 each time. The code that works for me in that case is:
li = [math.sin((2*math.pi/256)*i) for i in xrange(0,256)]