Selecting the first n items in a set

i has a large set element to iterate over. for debugging purposes, I would only like to repeat the first one, say ~ 10. For this, I created a list initialized from my set , selected the first 10 elements through [:10] and repeated it on the resulting list . Is there a more pythonic way to do this?

 mySet = set(df.SomeUniqueId) myList = list(mySet)[:10] for i, val in enumerate(myList): ... 
+5
source share
2 answers

I would use itertools.islice() . Creating an entire list, just to access the first items, seems wasteful to me.

 for i, val in enumerate(itertools.islice(mySet, 10)): 

EDIT:

If you want to randomly select (as opposed to randomly select) your ten items, try random.sample() .

 for i, val in enumerate(random.sample(mySet, 10)): 
+7
source

There are many ways to do this. Using a list (set (a)) will create a list that can take a lot of time depending on your set. But, since you only need iterations for a small number of loops, I would use an iterator and a counter:

 count = 0 for elem in iter(mySet): count = count + 1 if count == 10: break print elem 

This avoids the overhead of creating a long list, and the overhead of having a manual code for loop control is likely to be negligible.

+1
source

Source: https://habr.com/ru/post/1271746/


All Articles