Remove square brackets from list - python

I have this list:
list1 = [['123'], ['456'], ['789']]
I want to convert this list into a string and later store it into a column in a database in this form:
123 / 456 / 789
I tried doing this:
s2 = ", ".join(repr(e) for e in list1)
print(s2)
But this is what I'm getting:
['123'], ['456'], ['789']
Any ideas on what should I do next to get the desired output?

You are close, but what you want to do is flatten your list of lists first, then convert to string. Like this:
" / ".join([item for sublist in list1 for item in sublist])

You can use itertools.chain
import itertools
list1 = [['123'], ['456'], ['789']]
", ".join(itertools.chain(*list1))
# => '123, 456, 789'

list1 = [['123'], ['456'], ['789']]
st = [ '/' + x[0] for x in list1]
st = ''.join(st)
print(st)
output
/123/456/789

Since you have lists in the list, you need to get the first indice so this helps you
" / ".join(map(lambda x:x[0],list1))

If you specifically only ever want the first element of a sublist even if it's got more than one element, then I think this one-liner is the clearest:
s2 = ' / '.join( x[0] for x in list1 )

Related

Slice all strings in a list from their first '\n'

How to remove first RemoveThisX\n from list
['RemoveThis1\nDontRemove\nDontRemove','RemoveThis2\nDontRemove\nDontRemove', 'RemoveThis3\nDontRemove\nDontRemove', 'RemoveThis4\nDontRemove\nDontRemove']
Trying to remove RemoveThis1\n, RemoveThis2\n, RemoveThis3, RemoveThis4\n
Final result need to be
['DontRemove\nDontRemove','DontRemove\nDontRemove', 'DontRemove\nDontRemove', 'DontRemove\nDontRemove']
a_list = ['RemoveThis1\nDontRemove\nDontRemove','RemoveThis2\nDontRemove\nDontRemove', 'RemoveThis3\nDontRemove\nDontRemove', 'RemoveThis4\nDontRemove\nDontRemove']
result = [item[item.find('\n')+1:] for item in a_list]
print(result)
['DontRemove\nDontRemove', 'DontRemove\nDontRemove', 'DontRemove\nDontRemove', 'DontRemove\nDontRemove']
test_list = ['RemoveThis1\nDontRemove\nDontRemove','RemoveThis2\nDontRemove\nDontRemove', 'RemoveThis3\nDontRemove\nDontRemove', 'RemoveThis4\nDontRemove\nDontRemove']
result = ["\n".join(item.split("\n")[1:]) for item in test_list]
print(result)
Output will be:
['DontRemove\nDontRemove', 'DontRemove\nDontRemove', 'DontRemove\nDontRemove', 'DontRemove\nDontRemove']
assuming:
initial_list = ['RemoveThis1\nDontRemove\nDontRemove','RemoveThis2\nDontRemove\nDontRemove', 'RemoveThis3\nDontRemove\nDontRemove', 'RemoveThis4\nDontRemove\nDontRemove']
I would recommend using either the map function:
mapped_list = list(map(lambda x: x[x.find('\n') + 1:], initial_list))
or list comprehension:
comprehended_list = [string[string.find('\n') + 1:] for string in initial_list]
Both should produce the asked list.

Indexing list using tuple or list [duplicate]

If I have a list of lists and just want to manipulate an individual item in that list, how would I go about doing that?
For example:
List1 = [[10,13,17],[3,5,1],[13,11,12]]
What if I want to take a value (say 50) and look just at the first sublist in List1, and subtract 10 (the first value), then add 13, then subtract 17?
You can access the elements in a list-of-lists by first specifying which list you're interested in and then specifying which element of that list you want. For example, 17 is element 2 in list 0, which is list1[0][2]:
>>> list1 = [[10,13,17],[3,5,1],[13,11,12]]
>>> list1[0][2]
17
So, your example would be
50 - list1[0][0] + list1[0][1] - list1[0][2]
You can use itertools.cycle:
>>> from itertools import cycle
>>> lis = [[10,13,17],[3,5,1],[13,11,12]]
>>> cyc = cycle((-1, 1))
>>> 50 + sum(x*next(cyc) for x in lis[0]) # lis[0] is [10,13,17]
36
Here the generator expression inside sum would return something like this:
>>> cyc = cycle((-1, 1))
>>> [x*next(cyc) for x in lis[0]]
[-10, 13, -17]
You can also use zip here:
>>> cyc = cycle((-1, 1))
>>> [x*y for x, y in zip(lis[0], cyc)]
[-10, 13, -17]
This code will print each individual number:
for myList in [[10,13,17],[3,5,1],[13,11,12]]:
for item in myList:
print(item)
Or for your specific use case:
((50 - List1[0][0]) + List1[0][1]) - List1[0][2]
List1 = [[10,-13,17],[3,5,1],[13,11,12]]
num = 50
for i in List1[0]:num -= i
print num
50 - List1[0][0] + List[0][1] - List[0][2]
List[0] gives you the first list in the list (try out print List[0]). Then, you index into it again to get the items of that list. Think of it this way: (List1[0])[0].
for l in list1:
val = 50 - l[0] + l[1] - l[2]
print "val:", val
Loop through list and do operation on the sublist as you wanted.
new_list = list(zip(*old_list)))
*old_list unpacks old_list into multiple lists and zip picks corresponding nth element from each list and list packs them back.
to print every individual element in double list
list1=[[1,2,3],[4,5,6],[7,8,9]]
for i in range(len(list1)):
for j in range(len(list1[i])):
print(list1[i][j])

Combine two lists without duplicate values

list1 = ["palani", "samy","be"]
list2 = ["palani", "samys","be"]
def find_common(list1,list2):
for x in list1:
for y in list2:
if x == y :
list2.remove(x)
print" unique string 1:",list1
print" unique string 2:",list2
print" combained string 2:",list1.append(list2)
find_common(list1,list2)
Why am I getting None?
This could be accomplished by using set:
a = ['hello', 'world']
b = ['hello', 'universe']
unique = list(set(a + b))
print(unique)
# ['universe', 'hello', 'world']
Note: this won't work for a list of dictionaries!
import numpy as np
np.unique(list1+list2) # keeps only non dublicates
this is also keeps the order incase that was a priority
The list.append method modifies the list in-place and returns None. You should use the + operator to merge the two lists instead.
Change:
print" combained string 2:",list1.append(list2)
to:
print" combained string 2:",list1+list2
list3 = list1[:]
[list3.append(i) for i in list2 if i not in list1]
print(l3)
['palani', 'samy', 'be', 'samys']
you may try:
def find_common(list1,list2):
return list(set(list1+list2))
You can use set operations to achieve this.
unique = list(set(list1).symmetric_difference(set(list2)))

More elegant/pythonic way of unpacking a list?

Is there a more elegant/pythonic way of unpacking this list?
feature_set = [['flew'], ['homes'], ['fly home']]
Into this:
flew|homes|fly home
without this ugly code:
output = ''
for feature in feature_set:
if len(feature) < 2: output += ''.join(feature) + '|'
if len(feature) > 1: output += ' '.join(feature) + '|'
print(output[:-1])
Use chain.from_iterable to flatten list and then use str.join
Ex:
from itertools import chain
feature_set = [['flew'], ['homes'], ['fly home']]
print("|".join(chain.from_iterable(feature_set)))
Output:
flew|homes|fly home
first join each element of each inner list by map, and then join again for the map result
"|".join(map(lambda x: " ".join(x), feature_set))
I hope you want something like this.
'|'.join([inList[0] for inList in feature_set])

How to split elements of a list?

I have a list:
my_list = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
How can I delete the \t and everything after to get this result:
['element1', 'element2', 'element3']
Something like:
>>> l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
>>> [i.split('\t', 1)[0] for i in l]
['element1', 'element2', 'element3']
myList = [i.split('\t')[0] for i in myList]
Try iterating through each element of the list, then splitting it at the tab character and adding it to a new list.
for i in list:
newList.append(i.split('\t')[0])
Do not use list as variable name.
You can take a look at the following code too:
clist = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', 'element5']
clist = [x[:x.index('\t')] if '\t' in x else x for x in clist]
Or in-place editing:
for i,x in enumerate(clist):
if '\t' in x:
clist[i] = x[:x.index('\t')]
Solution with map and lambda expression:
my_list = list(map(lambda x: x.split('\t')[0], my_list))
I had to split a list for feature extraction in two parts lt,lc:
ltexts = ((df4.ix[0:,[3,7]]).values).tolist()
random.shuffle(ltexts)
featsets = [(act_features((lt)),lc)
for lc, lt in ltexts]
def act_features(atext):
features = {}
for word in nltk.word_tokenize(atext):
features['cont({})'.format(word.lower())]=True
return features

Categories