Asteroid
Asteroid

Reputation: 1118

How to extract sublists from a string in Python?

I have the following string: List =[[1], ['apple', 2], [3], [4], [5], [6], [7]]

How can I extract the sub-lists as following: s1 = [1] s2 = ['apple', 2] ... s7 = [7] ?

Thank you for your help.

Upvotes: 1

Views: 234

Answers (4)

merlin2011
merlin2011

Reputation: 75555

If you want to create 7 variables named s1 through s7, the most straightforward way is to do direct assignment.

s1 = List[0]
S2 = List[1]
...
S7 = List[6]

A second approach is to put all the assignments on one line and let python unpack the list, as described by @Lafada.

A third approach is to use exec, which may be more scalable for larger numbers of variables, although the value of all these separate names instead of the original list is not clear to me.

L = [[1], ['apple', 2], [3], [4], [5], [6], [7]]

for i in xrange(7):
  exec("s%d = L[%d]" % ((i+1), i))

Update: Based on OP's comment, he is starting with a string. Each of these approaches can be used, after we first convert the string to a list using ast.literal_eval.

import ast

List = "[[1], ['apple', 2], [3], [4], [5], [6], [7]]"
L = ast.literal_eval(List)

Upvotes: 3

dgsleeps
dgsleeps

Reputation: 700

Try this code

List=[[1], ['apple', 2], [3], [4], [5], [6], [7]]

output=""
for list_index in range(len(List)):
    output+="s%s = %s "%(list_index,List[list_index])


print output

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

Simply you could try the below.

s = []
s[:7] = List

Upvotes: 2

Neel
Neel

Reputation: 21243

You have to use unpacking

>>> L = [[1], ['apple', 2], [3], [4], [5], [6], [7]]
>>> s1, s2, s3, s4, s5, s6, s7 = L
>>> s1
[1]
>>> s2
['apple', 2]
>>> s7
[7]

Upvotes: 4

Related Questions