Hello I am trying to remove first and last 2 element of my list.
My list is: ['12','30','22','06','27','13','23','16','14','20','09','29','23']
and this is the code I am using:
dList.remove(dList[0])
dList.remove(dList[-1])
dList.remove(dList[-1])
It works right too many other list but in this list it returns:
['30', '22', '06', '27', '13', '16', '14', '20', '09', '29']
Instead of;
['30', '22', '06', '27', '13', '23', '16', '14', '20', '09',]
I noticed the last element is '23' and both '23' be removed but I don't know how to fix it. It should be work right because I remove first element, and last element, and last element again. I didn't use:
a = dList[0]
dList.remove(a)
a = dList[-1]
dList.remove(a)
a = dList[-1]
dList.remove(a)
The remove() method removes the first matching element (which is passed as an argument) from the list.
You have 23 repeated twice.
If you want to remove index you can use del in your example.it would be:
del dList[-1]
Why not using pop to pop out the last element of the list?
last_element = dList.pop()
semilast_element = dList.pop()
You can even put the index of the element you want to pop
first_element = dList.pop(0)
second_element = dList.pop(0)
Always refer to the original documentation
With:
dList = ['12','30','22','06','27','13','23','16','14','20','09','29','23']
...you could construct a new list with a slice (as previously suggested) like this:
dList = dList[1:-2]
...or you can do it in situ using pop() as follows:
dList.pop(0)
dList.pop()
dList.pop()
Related
i want to make a code (Lucky ticket, aka lottery) - with can generate random 6-dight number, after that - programm will check a list (with contain a lucky numbers for win: '11', '22', '33' and etc.) and say - are you win or not. But - theres one problem, i cant make if statement correctly, it always gives me error, not right result with i want. List are contain 9 values:
luckynumber = '11', '22', '33', '44', '55', '66', '77', '88', '99'.
try this:
if luckynumber in ["put all the lucky numbers in this list"]:
pass # do whatever you want
One problem you might be having is that in order to compare random_numberwith lucky_numbers, they both need to be strings i.e.,
lucky_numbers = ['11', '22', '33', '44', '55', '66', '77', '88', '99']
random_number = str(random_number) # assuming you already made random_number
You can then compare the two with any(), e.g.
result = any(r in random_number for r in lucky_number)
If you don't convert to random_number to a string, you'll get the error
TypeError: argument of type 'int' is not interable
I have a list of stings that have some repeating elements that I want to combine into a shorter list.
The original list contents look something like this:
lst = [['0.1', '0', 'RC', '100'],
['0.2', '10', 'RC', '100'],
['0.3', '5', 'HC', '20'],
['0.4', '5', 'HC', '20'],
['0.5', '5', 'HC', '20'],
['0.6', '5', 'HC', '20'],
['0.7', '5', 'HC', '20'],
['0.8', '5', 'HC', '20'],
['0.9', '10', 'RC', '100'],
['1.0', '0', 'RC', '100']]
After running it through the function it would become:
lst = [['0.1', '0', 'RC', '100'],
['0.2', '10', 'RC', '100'],
['0.3', '5', 'HC', '20'],
['0.9', '10', 'RC', '100'],
['1.0', '0', 'RC', '100']]
The list will always have this general structure, so essentially I want to combine the list based on whether or not the last 3 columns are exactly the same.
I want it to be a callable function so it would look some thing like:
def combine_list(lst):
if sublist[1:3] == next_sublist[1:3]:
let.remove(next_sublist)
My initial research on this showed many methods to remove a sublist based on its index, but that is not necessarily known before hand. I also found the re module, however I have never used it and unsure on how to implement it. Thank you in advanced
If you want to remove sub lists that are the same for the last three elements and consecutive, you would need itertools.groupby keyed on the last three elements:
from itertools import groupby
[next(g) for _, g in groupby(lst, key=lambda x: x[1:])]
#[['0.1', '0', 'RC', '100'],
# ['0.2', '10', 'RC', '100'],
# ['0.3', '5', 'HC', '20'],
# ['0.9', '10', 'RC', '100'],
# ['1.0', '0', 'RC', '100']]
Maybe just use a set to keep track of duplicates?
def combine_list(lst):
out = []
seen = set()
for item in lst:
if not tuple(item[1:]) in seen:
out.append(item)
seen.add(tuple(item[1:]))
return out
Lists are a mutable data structure. And so there is no guarantee that the contents of a list does not change over time. That means it cannot be used in a hashing function (which the set uses). The tuple, on the other hand, is immutable, and hence hashable.
for index in range(len(lst) - 1, 0, -1):
if lst[index][1:] == lst[index - 1][1:]:
lst.pop(index)
By going through the list backwards, we remove the problems with indices changing when we remove elements. This results in an in-place reduction.
If you'd like to make a new list, this can be done via list comprehension following the same idea, but since we're not doing it in place, we don't have to work in reverse:
lst[0] + [lst[ind] for ind in range(1, len(lst)) if lst[ind][1:] != lst[ind-1][1:]]
Again, lst[0] is trivially non-duplicate and therefore automatically included.
def combine_list(ls):
cpy = ls[:]
for i, sub in enumerate(ls[:len(ls) - 1]):
if sub[1:] == ls[i + 1][1:]:
cpy.remove(ls[i + 1])
return cpy
This function should work. It creates a new copy of the list, to avoid modifying the original. Then it iterates over the original list (except the last value), as that stays the same.
It then checks if the last values of the list are equal to the last values of the next list. If they are, the next list is deleted.
The function then returns the new list.
all_tags = ['24', '02', '26', '03', '33', '32', '31', '30', '29', '68', '11']
ref_tag = str('24')
union_tags = set(all_tags) | set(ref_tag)
left_tags = set(all_tags) - set(ref_tag)
print(union_tags)
print(left_tags)
The above is the simple code which I expect elements in union_tags should be the same as those in all_tags. However, the result is
set
(['24', '02', '26', '03', '33', '32', '31', '30', '29', '68', '2', '4', '11'])
The union_tags instead contains two extra elements '2' and '4', which I think it is the result splitting the str '24'.
Again, left_tags should exclude element '24'. However, the result still have the '24'.
Please let me know why. I use the python 2.7 as the interpreter.
Set function accept an iterable with hashable items and convert it to a set object, and since strings are iterables when you pass the string 24 to your set function it converts your string to following set:
{'2', '4'}
And at last the unioin of this set with all_tags would contain items 2 and 4.
If you want to put the 24 in a set as one item you can use {} in order to create your expected set:
>>> ref_tag = {'24'}
set(['24'])
I am trying to take a list of strings, and prepend an amount of zeroes to the front so that they are all the same length. I have this:
def parity(binlist):
print(binlist)
for item in binlist:
if len(item)==0:
b='000'
elif len(item)==1:
b='00{}'.format(item)
elif len(item)==2:
b='0{}'.format(item)
binlist.remove(item)
binlist.append(b)
return binlist
This is binlist:
['1', '10', '11', '11']
and i want to get this after running it:
['001', '010', '011', '011']
but I get this:
['10', '11', '11', '001']
which really confuses me.
thanks for any help at all.
Try this:
>>> n = "7"
>>> print n.zfill(3)
>>> "007"
This way you will have always a 3 chars string (if the number is minor than 1000)
http://www.tutorialspoint.com/python/string_zfill.htm
The native string formatting operations allow you to do this without all the trouble you're putting in. Here's an example.
x = ['1', '10', '11', '11']
print ["{:>03s}".format(t) for t in x]
['001', '010', '011', '011']
This is caused because you are deleting the elements in the list while iterating through the list using a for loop. Doing so does not iterate over the full list. You can use a while loop to solve this problem.
You can do this in a one-liner using zfill:
>>> map(lambda binlist_item: binlist_item.zfill(3), ['1', '10', '11', '11'] )
['001', '010', '011', '011']
Fill with zeros for each item in the list
binlist = [i.zfill(3) for i in binlist]
I have 2 lists: 1 of which is a lists of lists. They are as follows-
lists_of_lists = ['1', '4', '7', '13', '16', '21', '32', '36'],['3', '6', '8', '14', '22', '26', '31', '40']
just_a_list =['THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOG', 'IWOULDLOVETOGETOVERWITHTHISASSOONASPOSSIBLE']
The lists_of_lists are used for slicing the elements of just_a_list such that:
['1', '4', '7', '13', '16', '21', '32', '36'] would slice the string 'THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOG' as follows
'1' - '4' - 'HEQU'
'7' - '13' - 'KBROWNF'
'16' - '21' - 'JUMPED'
'32' - '36' - 'ZYDOG'
points to note-
Each list in list_of_lists will have an even number of numbers.
The list at i'th position in list_of_lists will belong to the
string present at the i'th position in just_a_list.
Please help me out as to how do I carry out the process described above..
Thanks
Use zip() to combine the string and slice lists, then use a zip() plus iter() trick to pair the start and stop values:
for slicelist, text in zip(lists_of_lists, just_a_list):
for start, stop in zip(*([iter(slicelist)]*2)):
print(text[int(start):int(stop) + 1])
Note that we have to add 1 to the stop index, as your appear to need it to be inclusive, while in Python the stop index is exclusive.
This gives:
>>> for slicelist, text in zip(lists_of_lists, just_a_list):
... for start, stop in zip(*([iter(slicelist)]*2)):
... print(text[int(start):int(stop) + 1])
...
HEQU
KBROWNF
JUMPED
YDOG
ULDL
VETOGET
HTHIS
ONASPOSSIB
If I understand you right:
>>> ls = just_a_list =['THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOG', 'IWOULDLOVETOGETOVERWITHTHISASSOONASPOSSIBLE']
>>> ls[0]
'THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOG'
# so we do
# your index was off by one
>>> ls[0][1:5]
'HEQU'
>>> ls[0][7:14]
'KBROWNF'