2

my code looks something like this:

documents=set()
finals = []
temporary_set= set()
temporary_set.add(i)
finals.append(documents.intersection(temporary_set))

when i want to get all values from the finals list i use:

for final in finals:
    print (final)

This returns however the items as a set item within a list. like this:

[{27309053}, {23625724}, {25051134}]

How can i make it that the curly brackets will be omitted and that my result will look like this:

[27309053, 23625724, 25051134]

???

4 Answers4

4

You can change

finals.append(documents.intersection(temporary_set))

to

finals.extend(documents.intersection(temporary_set))

which will add each element of that intersection to the list, rather than the intersection itself.

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
2

You can flatten your list of sets using itertools.chain.from_iterable:

import itertools

x = [{27309053}, {23625724}, {25051134}]

list(itertools.chain.from_iterable(x))
# [27309053, 23625724, 25051134]
sacuL
  • 49,704
  • 8
  • 81
  • 106
  • 1
    they could but it would better to go back a step on not create a list of sets in the first place – Chris_Rands Nov 08 '18 at 18:00
  • I agree. But the question was essentially that they end up with a list of sets, and want it turned into a flat list... – sacuL Nov 08 '18 at 18:01
  • 1
    if you intupret the question that way, then it's a common duplicate https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python (Patrick's approach is better IMO) – Chris_Rands Nov 08 '18 at 18:02
1

Fixing the code upstream by using extend is the way to go here.

If you end up with a list

l = [{27309053}, {23625724}, {25051134}]

where you can't modify how it's created, you can use iterable unpacking like this:

>>> l = [{27309053}, {23625724}, {25051134}]
>>> [x for x, in l]
>>> [27309053, 23625724, 25051134]
timgeb
  • 76,762
  • 20
  • 123
  • 145
0

You can use a list comprehension:

l = [{27309053}, {23625724}, {25051134}]

[x for sl in l for x in sl]  # evaluates to [27309053, 23625724, 25051134]
Alex
  • 18,484
  • 8
  • 60
  • 80