I have a list of values in this format:
['11111-11111','22222-22222','33333-33333']
How do I strip the values in the list so I only have the first 5 numbers of each value in the list?
Looking for:
['11111','22222','33333']
You can use a list comprehension and slice each element in your list:
In [16]:
l=['11111-11111','22222-22222','33333-33333']
[x[:5] for x in l]
Out[16]:
['11111', '22222', '33333']
a call to str.split would work too:
In [17]:
l=['11111-11111','22222-22222','33333-33333']
[x.split('-')[0] for x in l]
Out[17]:
['11111', '22222', '33333']
If you would like a very simple solution, it could be like that:
yourList = ['11111-11111','22222-22222','33333-33333']
newList = []
for item in yourList:
newList.append(item[:5])
print(newList)
The output is ['11111', '22222', '33333']
Related
Search through the list and remove everything else inclusive and after either Audi or Mazda or Suzuki. Please note Only one of the 3 can be in the list but not two or all of them. Just one of them
First Scenario: if it's Audi,
Give a list (list items are random):
lst = ["Nissan","Chevrolet","Audi","Mercedes","BMW","Subaru","Mitsubishi"]
Expected result:
new_lst = ["Nissan","Chevrolet"]
Scenario 2 : If it's Suzuki.
Expected result
lst = ["Nissan","Chevrolet","Mercedes","BMW","Subaru","Suzuki","Mitsubishi"]
new_lst = ["Nissan","Chevrolet","Mercedes","BMW","Subaru"]
etc etc
You can use itertools.takewhile to crate a new list and 'break' out at the appropriate point
>>> from itertools import takewhile
>>> lst = ["Nissan","Chevrolet","Audi","Mercedes","BMW","Subaru","Mitsubishi"]
>>> list(takewhile(lambda x: x != "Audi", lst))
['Nissan', 'Chevrolet']
Use list slicing with list.index
Ex:
lst = ["Nissan","Chevrolet","Audi","Mercedes","BMW","Subaru","Mitsubishi"]
print(lst[:lst.index("Audi")])
lst = ["Nissan","Chevrolet","Mercedes","BMW","Subaru","Suzuki","Mitsubishi"]
print(lst[:lst.index("Suzuki")])
Output:
['Nissan', 'Chevrolet']
['Nissan', 'Chevrolet', 'Mercedes', 'BMW', 'Subaru']
I have tried as below , it can be done using list comprehension [also without using in-build functions and techniques like [::-1] ], but want to do it using nested for loops as below ?
l=['temp','test']
l1=[]
for t in l:
for i in t:
l1.append(str(i[::-1]))
print(l1)
input: ['test','temp']
required output : ['pmet','tset']
In order to reverse the order of the elements in the list, you can use reverse:
for i in reversed(array):
print(i)
Or, you can use array.reverse().
in order to reverse each string, you can use [::-1], for example:
txt = "Hello World"[::-1]
print(txt)
output:
dlroW olleH
Looking at the code you added, you can do something like this:
l=['temp','test']
reverse_l=[]
reverse_l = [item[::-1] for item in l] # This is list comprehensions, you can read about it in the link at the end of the answer
reverse_l.reverse()
print(l)
print(reverse_l)
output:
['temp', 'test']
['tset', 'pmet']
A solution without list comprehension:
l=['temp','test']
reverse_l=[]
for item in l:
item = item[::-1]
reverse_l.append(item)
reverse_l.reverse()
print(l)
print(reverse_l)
You can find information about list Comprehensions in python here.
Using nested loops:
l=['temp','test']
print([''.join([w[i] for i in range(len(w)-1, -1, -1)]) for w in reversed(l)])
Output:
['pmet', 'tset']
try this
l=['temp','test']
l1=[]
for t in l:
l1.append(t[::-1])
print(l1)
You don't need a nested loop:
l = ['temp', 'test']
l1 = [
word[::-1]
for word in l
]
print(l1)
output:
['pmet', 'tset']
You can try the following :
input_list = ['test', 'temp']
input_list.reverse()
print(list(map(lambda x: x[::-1], input_list)))
for i in range(len(l)):
l[i] = l[i][::-1]
l = l[::-1]
you don't need nested loops for desired output you have given.
I have a list of strings
my_list = ['1Jordan1', '2Michael2', '3Jesse3'].
If I should delete the first and last character, how would I do it in python??
If I understand correctly:
mylist = ['1Jordan1', '2Michael2', '3Jesse3']
mylist = list(map(lambda item: item[1:-1], mylist))
print(mylist) # ['Jordan', 'Michael', 'Jesse']
This uses slice syntax to get the characters between the first and last character, and uses map to apply the slice to each string in the list.
If you'd like something slightly more readable (thanks to the comments), use a list comprehension:
mylist = ['1Jordan1', '2Michael2', '3Jesse3']
mylist = [item[1:-1] for item in mylist]
print(mylist) # ['Jordan', 'Michael', 'Jesse']
You would use slicing. I would use [1:-1].
I have a large list like this:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
I'm trying to remove all numbers within the lists of this list. So I made a list of numbers as strings from 1 to 100:
def integers(a, b):
return list(range(a, b+1))
numb = integers(1,100)
numbs = []
for i in range(len(numb)):
numbs.append(str(numb[i])) # strings
numbs = ['1','2',....'100']
How can I iterate through lists in mylist and remove the numbers in numbs? Can I use list comprehension in this case?
If number is always in the end in sublist
mylist = [ x[:-1] for x in mylist ]
mylist = [[item for item in sublist if item not in numbs] for sublist in mylist] should do the trick.
However, this isn't quite what you've asked. Nothing was actually removed from mylist, we've just built an entirely new list and reassigned it to mylist. Same logical result, though.
If numbers are always at the end and only once, you can remove the last item like:
my_new_list = [x[:-1] for x in mylist]
If there is more (of if they are not ordered), you have to loop thru each elements, in that case you can use:
my_new_list = [[elem for elem in x if elem not in integer_list] for x in mylist]
I would also recommend to generate the list of interger as follow :
integer_list = list(map(str, range(1, 100)))
I hope it helps :)
Instead of enumerating all the integers you want to filter out you can use the isdigit to test each string to see if it really is only numbers:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
mylist2 = [[x for x in aList if not x.isdigit()] for aList in mylist]
print mylist2
[['pears', 'apples'], ['grapes', 'trees', 'bears']]
If you have the following list:
mylist = [['pears','apples','40'],['grapes','trees','90','bears']]
numbs = [str(i) for i in range(1, 100)]
Using list comprehension to remove element in numbs
[[l for l in ls if l not in numbs] for ls in mylist]
This is a more general way to remove digit elements in a list
[[l for l in ls if not l.isdigit()] for ls in mylist]
How do you turn a list of strings into a list of sublist of strings?
For example:
List_of_Strings = ['abc','def','ghi']
Desired Output:
[['abc'],['def'],['ghi']]
My hack to get it is:
List_of_Sublist_of_Strings = [(str(x)+",").split(",") for x in List_of_Strings]
Produces:
[['abc', ''], ['def', ''], ['ghi', '']]
This produces an unwanted empty item in the sublists, but perhaps it's not possible to create a list of sublists in which the sublists only have one item.
You need to put those strings in [] there, and it's done.
>>> lis = ['abc','def','ghi']
>>> [[x] for x in lis]
[['abc'], ['def'], ['ghi']]
Use a list comprehension like so:
>>> lst = ['abc','def','ghi']
>>> [[x] for x in lst]
[['abc'], ['def'], ['ghi']]
>>>
Putting x in [] places it in a list of its own.