This may seem odd, but I am trying to remove a part of an item contained in a list. Basically, I am trying to remove a specific character from multiple list elements. For example
list = ['c1','c2','c3','d1','s1']
list.remove('c')
I know that doing that wouldn't work, but is there any way to remove the "c"s in the list, and only the "c"s in Python 3?
lst = [s.replace('c','') for s in lst]
# ['1','2','3','d1','s1']
List comprehensions are your friend. Also note the "list" is a keyword in Python, so I highly recommend you do not use it as a variable name.
Use list comprehensions,
list = ['c1','c2','c3','d1','s1']
list_ = [ x for x in list if "c" not in x ] # removes elements which has "c"
print list_ # ['d1', 's1']
list1 = ['c1','c2','c3','d1','d2']
list2 = []
for i in range (len(list1)):
if 'c' not in list1[i]:
list2.append(list1[i])
print (list2) #['d1', 'd2']
and also this link may helpful
Link one
Related
I have a list [['user44'],['user204'],['user355'],['user395'],['user452']]
I want to convert it to [ 'user44', 'user204' , 'user355', 'user395', 'user452']
Any help on this?
Assuming userXYZ is always a string
lst = [['user44'],['user204'],['user355'],['user395'],['user452']]
lst1 = [y for x in lst for y in x]
print(lst1)
output
['user44', 'user204', 'user355', 'user395', 'user452']
Every element of the list is a list itself, with one element.
You can take that element and create a new list using list comprehension.
new_list=[elem[0] for elem in old_list]
This will go over all elements of the list (which are themselves, lists), and extract the strings into a new list.
This will allow for use encase you need to join more than 1 list.
x = [''.join(x[i] for i in range(len(x)))]
If I have this list,
list01 = ['GAGGT','TCCGT','ABECF']
I want to make each element in the list to split, but still remain in the same box of list.
Like this:
listalt = [['G','A','G','G','T'],['T','C','C','G','T'],['A','B','E','C','F']]
listalt = [list(i) for i in list01]
This is a list comprehension, and uses the fact that list can take an iterable (like a string) and turn it into a list
You can use this :
final_list=[]
for item in list01:
final_list.append(list(item))
print(final_list)
which is same as :
print([list(item) for item in list01])
I have a dictionary similar to this
x ={'1': [['a','b'],['ac','d']], '2' : [['p','qa'],['r','s']]}
And I would like to access the individual strings i.e. a,b etc , compare if it has "a" in it, delete those.
The main question is - how do I access the strings? How do I change it?
I tried using nested loops, but was unable to change, as I guess assignment stmts do not work that way.
Any idea how to proceed with such situation?
Edit : The naive approach I used -
for item in x:
for ele in x[item]:
for i in ele:
i = #assign new value here using regex comparison
But when I try to print x after this, it stays same.
Obviously. assignment statements do not work this way. Any idea about how should I access the elements to change it?
>>> x ={'1': [['a','b'],['ac','d']], '2' : [['p','qa'],['r','s']]}
>>> for key in x:
... for n, item in enumerate(x[key]):
... x[key][n] = list(filter(lambda l: 'a' not in l, x[key][n]))
...
>>> x
{'2': [['p'], ['r', 's']], '1': [['b'], ['d']]}
In your example,
for item in x:
for ele in x[item]:
for i in ele:
i = #assign new value here using regex comparison
i is a copy of the string in ele, so assigning to it has no effect on the original. You need to modify the list ele. Possibly, ele[ele.index(i)] = #whatever. Note, however, that this will not work correctly if you have identical values in the list. It will only change the first one.
Not sure what you're actually trying to do, but it may be easier to use a list comprehension, at least for the innermost list. This will allow you to change each element of the innermost list. Perhaps,
for item in x.values():
for ele in item:
ele[:] = [#whatever for i in ele]
where ele[:] is needed to change the original inner list (just ele won't work), and I used the more Pythonic x.values() when we actually wanted the values, not the keys.
In this example:
sorted_data = [files.data[ind] for ind in sort_inds]
May someone please provide an explanation as to how the expression behind the for loop is related or how it is working, thanks.
It's called a List Comprehension
In other words
sorted_data = [files.data[ind] for ind in sort_inds]
is equivalent to:
sorted_data = []
for ind in sort_inds:
sorted_data.append(files.data[ind])
It's just a lot more readable using the comprehension
ok so here is a simple example:
say i have a list of ints:
nums = [1,2,3]
and i do this:
[i**2 for i in nums]
it will output:
[1, 4, 9]
this is equivalent to this:
for i in nums:
list.append(i**2)
because it iterated through the list and squared each item in the list
another example:
say i have a list of strings like this:
list1 = ['hey, jim','hey, pam', 'hey dwight']
and I do this:
[phrase.split(',') for phrase in list1]
this will output this list:
[['hey', ' jim'], ['hey', ' pam'], ['hey dwight']]
this is equivalent too:
for phrase in list1:
new_phrase = phrase.split(',')
list.append(new_phrase)
it went through and made a list out of each item but it used split on each item
its basically a compacted for loop and instead of using append() it just creates the list!. it is much more readable and takes less lines
learn more here
It means for every item in this case ind present in sort_inds, pass it as a parameter to the function files.data[ind].
Save the result in a list (sorted_data)
How can I extract elements in a list of lists and create another one in python. So, I want to get from this:
all_list = [['1 2 3 4','2 3 4 5'],['2 4 4 5', '3 4 5 5' ]]
a new list like this:
list_of_lists = [[('3','4'),('4','5')], [('4','5'),('5','5')]]
Following is what I did, and it doesn't work.
for i in xrange(len(all_lists)):
newlist=[]
for l in all_lists[i]:
mylist = l.split()
score1 = float(mylist[2])
score2 = mylist[3]
temp_list = (score1, score2)
newlist.append(temp_list)
list_of_lists.append(newlist)
Please help. Many thanks in advance.
You could use a nested list comprehension. (This assumes you want the last two "scores" out of each string):
[[tuple(l.split()[-2:]) for l in list] for list in all_list]
It could work almost as-is if you filled in the value for mylist -- right now its undefined.
Hint: use the split function on the strings to break them up into their components, and you can fill mylist with the result.
Hint 2: Make sure that newlist is set back to an empty list at some point.
Adding to eruciforms answer.
First remark, you don't need to generate the indices for the all_list list. You can just iterate over it directly:
for list in all_lists:
for item in list:
# magic stuff
Second remark, you can make your string splitting much more succinct by splicing the list:
values = item.split()[-2:] # select last two numbers.
Reducing it further using map or a list comprehension; you can make all the items a float on the fly:
# make a list from the two end elements of the splitted list.
values = [float(n) for n in item.split()[-2:]]
And tuplify the resulting list with the tuple built-in:
values = tuple([float(n) for n in item.split()[-2:]])
In the end you can collapse it all to one big list comprehension as sdolan shows.
Of course you can manually index into the results as well and create a tuple, but usually it's more verbose, and harder to change.
Took some liberties with your variable names, values would tmp_list in your example.