I have a string
s = 'A;B;C1,C2,C3;D'
I want to split this string in a 2D list, so the result would be:
alist = [['A'], ['B'], ['C1', 'C2', 'C3'], ['D']]
I can't do that with
'A;B;C1,C2,C3;D'.split(';').split(',')
because AttributeError: 'list' object has no attribute 'split'
Is there an easy way to fill this 2d list at once?
You could use a list comprehension
>>> res = [s1.split(',') for s1 in s.split(';')]
>>> res
[['A'], ['B'], ['C1', 'C2', 'C3'], ['D']]
Related
I have a list of strings like this:
lst = ["this", "that", "cat", "dog", "crocodile", "blah"]
And I have another list of integers like:
index_nr = [2,3]
My goal is to take the numbers from index_nr and get the list items from lst with the corresponding index number. If we stick to the example above, the desired output would be
['cat', 'dog']
Given that, 0: "this", 1: "that", 2: "cat", 3: "dog", 4: "crocodile", and 5: "blah".
I know that:
print(lst[2:4])
would throw the desired output, but I'm not sure how to use the values in index_nr to achive the same outcome.
You can use list comprehension:
lst = ["this", "that", "cat", "dog", "crocodile", "blah"]
index_nr = [2, 3]
out = [lst[index] for index in index_nr]
print(out)
Prints:
['cat', 'dog']
Or standard for-loop:
out = []
for index in index_nr:
out.append(lst[index])
print(out)
You could index lst inside index_nr like this: index_nr = [lst[2],lst[3]]
I have a list name list1:
list1 = [['DC1', 'C4'], ['DC1', 'C5'], ['DC3', 'C1'], ['DC3', 'C2'], ['DC3', 'C3']]
I want to make two new lists:
list1_1 = ['DC1', 'C4', 'C5']
list1_2 = ['DC3', 'C1', 'C2', 'C3']
can anyone please show me how to do?
thank you.
this can solve your problem. note: this is not an optimized one
yourlist = [['DC1', 'C4'], ['DC1', 'C5'], ['DC3', 'C1'], ['DC3', 'C2'], ['DC3', 'C3']]
temp_dict = {}
for i in yourlist:
if i[0] not in temp_dict:
temp_dict.update({i[0]:[i[1]]})
else:
temp_dict[i[0]].append(i[1])
final_list =[]
for i,j in temp_dict.items():
temp_list =[i]
for k in j:
temp_list.append(k)
final_list.append(temp_list)
list1_1 = final_list[0]
list1_2 = final_list[1]
Output:
list1_1
['DC1', 'C4', 'C5']
list1_2
['DC3', 'C1', 'C2', 'C3']
Building on Tamil Selvan's answer, but using a defaultdict for simplicity and list concatenation instead of appends for the big list.
from collections import defaultdict
list1 = [['DC1', 'C4'], ['DC1', 'C5'], ['DC3', 'C1'], ['DC3', 'C2'], ['DC3', 'C3']]
# First we create a dict containing the left terms as keys and the right terms as values.
d = defaultdict(list)
for (key, value) in list1:
d[key].append(value)
print(d)
# {'DC1': ['C4', 'C5'],
# 'DC3': ['C1', 'C2', 'C3']}
# Then for each key, we create a list of values with the key as first item.
lists = []
for key, values in d.items():
sublist = [key, *values]
lists.append(sublist)
print(lists)
# [['DC1', 'C4', 'C5'],
# ['DC3', 'C1', 'C2', 'C3']]
# Finally, you can easily take the sublist that you want.
list1_1, list1_2 = lists
I am trying to store a string variable containg some names, I want to store the respective variable in a list and print it, but am unable print the values which are stored in variable.
name='vsb','siva','anand','soubhik' #variable containg some names
lis=['name'] # storing the variable in a list
for x in lis:
print(x) #printing the list using loops
Image:
Maybe dictionary? Try this
variable_1 = "aa"
variable_2 = "bb"
lis = {}
lis['name1'] = variable_1
lis['name2'] = variable_2
for i in lis:
print(i)
print(lis[i])
Your name variable is actually a tuple.
Example of tuple declaration:
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
Example of list declaration:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
For a better understanding you should read The Python Standard Library or do a tutorial.
For your problem maybe the dictionary is the solution:
# A tuple is a sequence of immutable Python objects
name='vsb','siva','anand','soubhik'
print('Tuple: ' + str(name)) # ('vsb', 'siva', 'anand', 'soubhik')
# This is a list containing one element: 'name'
lis=['name']
print('List: ' + str(lis)) # ['name']
# Dictionry with key 'name' and vlue ('vsb','siva','anand','soubhik')
dictionary={'name':name}
print('Dictionary: ' + str(dictionary))
print('Dictionary elements:')
print(dictionary['name'])
print('Tuple elements:')
for x in name:
print(x)
print('List elements:')
for x in lis:
print(x)
Output
Tuple: ('vsb', 'siva', 'anand', 'soubhik')
List: ['name']
Dictionary: {'name': ('vsb', 'siva', 'anand', 'soubhik')}
Dictionary elements:
('vsb', 'siva', 'anand', 'soubhik')
Tuple elements:
vsb
siva
anand
soubhik
List elements:
name
I have a list of lists like this
list1 = [['I am a student'], ['I come from China'], ['I study computer science']]
len(list1) = 3
Now I would like to convert it into a list of string like this
list2 = ['I', 'am', 'a', 'student','I', 'come', 'from', 'China', 'I','study','computer','science']
len(list2) = 12
I am aware that I could conversion in this way
new_list = [','.join(x) for x in list1]
But it returns
['I,am,a,student','I,come,from,China','I,study,computer,science']
len(new_list) = 3
I also tried this
new_list = [''.join(x for x in list1)]
but it gives the following error
TypeError: sequence item 0: expected str instance, list found
How can I extract each word in the sublist of list1 and convert it into a list of string? I'm using python 3 in windows 7.
Following your edit, I think the most transparent approach is now the one that was adopted by another answer (an answer which has since been deleted, I think). I've added some whitespace to make it easier to understand what's going on:
list1 = [['I am a student'], ['I come from China'], ['I study computer science']]
list2 = [
word
for sublist in list1
for sentence in sublist
for word in sentence.split()
]
print(list2)
Prints:
['I', 'am', 'a', 'student', 'I', 'come', 'from', 'China', 'I', 'study', 'computer', 'science']
Given a list of lists where each sublist contain strings this could be solved using jez's strategy like:
list2 = ' '.join([' '.join(strings) for strings in list1]).split()
Where the list comprehension transforms list1 to a list of strings:
>>> [' '.join(strings) for strings in list1]
['I am a student', 'I come from China', 'I study computer science']
The join will then create a string from the strings and split will create a list split on spaces.
If the sublists only contain single strings, you could simplify the list comprehension:
list2 = ' '.join([l[0] for l in list1]).split()
I am facing a problem to convert from List to tuple. For example i have lists like this
['1', '9']
['2']
['3']
['4']
I want output like this
[(1,9),(2),(3),(4)]
Kindly help me. I am not getting any way.
If you have a list 'l' then you can call the builtin function 'tuple' on it to convert to a tuple
l = [1,2]
tup = tuple(l)
print tup # (1,2)
if you have a list of list l = [['1', '9'], ['2'], ['3'], ['4']]
you can do :
l = [['1', '9'], ['2'], ['3'], ['4']]
tups = map(lambda x: tuple(x), l)
print tups # [(1,9),(2),(3),(4)]