-3

I have a list of lists that looks as follows (I hope I'm right when I said list of lists):

['[175', '178', '182', '172', '167', '164]', "['b']"]

How can I concatenate the two lists? That is, having a list that looks as follows:

[175, 178, 182, 172, 167, 164, b]

Any thoughts?

Thanks.

4
  • 3
    What are these [s in '[175 doing? Oct 18, 2018 at 22:44
  • That was a portion of the output that resulted from: X = np.array([[i[0],i[1]] for i in images])
    – Simplicity
    Oct 18, 2018 at 22:45
  • 3
    Note that your input is not two lists. It is a list of strings. Oct 18, 2018 at 22:48
  • 2
    @Simplicity: It looks like you converted the numpy array to a string. Please do not do that: you here "lose information and structure", making reconstructing the array much harder. Oct 18, 2018 at 22:48

3 Answers 3

3

First, note that that's not a list of lists, but just a list of strings that, when concatenated, might look like one or more (nested) lists, in particular with those [ and ] in the first and last element. Thus, you could join those strings with , to a string that actually represents a pair or tuple of lists, and then eval or ast.literal_eval those. Then just use a list comprehension to flatten that actual list of lists.

>>> lst = ['[175', '178', '182', '172', '167', '164]', "['b']"]

>>> ','.join(lst)
"[175,178,182,172,167,164],['b']"

>>> ast.literal_eval(','.join(lst))
([175, 178, 182, 172, 167, 164], ['b'])

>>> [x for sub in ast.literal_eval(','.join(lst)) for x in sub]
[175, 178, 182, 172, 167, 164, 'b']
1
  • sharpy eyes you have...
    – BladeMight
    Oct 18, 2018 at 22:55
0

list concatenations work with a + so ...

lsts = ['[175', '178', '182', '172', '167', '164]', "['b']"]
new_lsts = []
for i in lsts:
  new_lsts += i

Also this similar question has been asked here many times.

Here

and here

and probably several other times

2
  • I don't think this will connect the "items"?
    – Simplicity
    Oct 18, 2018 at 22:52
  • it does if your lists were actually lists of lists rather than lists of strings Oct 18, 2018 at 22:57
-1

In python you can use + to concat them:

a = [2,5,6]
b = [6,1,4]
c = a+b
print(c)
1
  • Why downvote? it just doesn't show the for loop upon the list of lists, i wanted the OP to get to it.
    – BladeMight
    Oct 18, 2018 at 22:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.