How can I insert item into the array if its not already there?
This is what I tried:
[..]
k = []
for item in myarray:
if not item in k:
print("Item is in array already.")
k[] = item
Your code has the right idea but just use k.append(item) instead of k[] = item.
Also it is cleaner to say if item not in k:
k[] = item is invalid syntax. All you need to do is just remove that line and use list.append()
for item in myarray:
if not item in k:
print("Item is in array already.")
k.append(item)
list.append() adds an item to the end of the list.
If you don't care about the order of the items in the list, you can convert it to a set to filter out any duplicates.
k = list(set(myarray))
Or if k already contains something...
k = [...] # optionally non-empty array
k = list(set(k) | set(myarray))
What that does is convert both myarray and k into sets, and combines them so that the result is a unique list that containing the contents of both k and myarray.
Related
I want to remove some items from specific places. for example, I have list [a,b,c,d,e,f,g,h,i]. the number of items in this list constantly changes.
That is why I need special method that is helps to remove items from same place. Now the modified list should be like that: list [a,b,c,d,e,f,i]. g and h should always be removed.
Do you want to remove the second- and third-last item from the list?
This can be achieved like this:
del lst[-3:-1]
If you create dictionaries with necessary indexes you can use them to create a new list.
lst = ['a','b','c','d','e','f','g','h','i']
other = ['a','y','b','c','d','e','g','h','l']
indexed_lst = {i: item for i, item in enumerate(lst)}
indexed_other = {i: item for i, item in enumerate(other)}
[item for i, item in indexed_lst.items() if indexed_lst.get(i, None) != indexed_other.get(i, None) ]
You can remove from the list either by index or by value. In either case it is a good practice to check if the index/value is present in the list. As for removing an item from the list you could use one of the below based on what info is available / output required.
Remove an item by index and get its value: pop()
# where i is the index of the value to be removed
if i < len(lst)
result = l.pop(i)
Remove items by index or slice: del()
# where i is the index of the value to be removed
if i < len(lst) :
lst.del(i)
Remove an item by value: remove()
# where `h` is the value to be removed
if 'h' in lst:
lst.remove('h')
You could also remove items from a list based on a given condition, in which case you could use list comprehensions
l = list(range(10))
# Remove all the odd numbers
print([i for i in l if i % 2 != 0])
ahh i understand your answer, if you use index like this
Remove items by index, specific place
lst = ['a','b','c','d','e','f','g','h','i']
lst = [item for index,item in enumerate(lst) if index != 6 and index != 7]
print(lst)
or Remove items by Value
lst = ['a','b','c','d','e','f','g','h','i']
lst = [item for item in lst if item != 'g' and item != 'h']
print(lst)
Use the .pop() to pop off any given index off the list
lst = ['a','b','c','d','e','f','g','h','i']
lst = [item for item in lst if item != 'g' and item != 'h']
print(lst)
if you have more input, tell me
In python 3, I am trying to create an array of elements, where each element consists of two values. These values are not really key-value pairs because they are equally related to each other, meaning value 1 could be the key for value two, just as value two could be the key to value one and so I didn't think a dictionary was appropriate.
my_list = [ (VALUE1, OFFSET1), (VALUE2, OFFSET2) ]
def printList(list):
for item in list:
print(item)
How could I collect the VALUE and OFFSET "values" separately? Such as
theValue = list[0].VALUE
theOffset = list[0].OFFSET
I'm thinking an array of structs perhaps?
You can use zip, which transposes the list and collects elements at the same position to one element in the result:
value, offset = zip(*my_list)
value
#('VALUE1', 'VALUE2')
offset
#('OFFSET1', 'OFFSET2')
def printList(my_list):
for item in my_list:
print('Value ', item[0])
print('Offset ', item[1])
The for loop iterates through my_list. Each element in the loop is received as tuple like (VALUE, OFFSET) in the variable item. So item[0] is VALUE and item[1] is OFFSET. And we print it.
I'll do this like:
my_list = [ ("VALUE1", "OFFSET1"), ("VALUE2", "OFFSET2") ]
def printList(my_llst):
values = []
ofts = []
for item in my_llst:
values.append(item[0])
ofts.append(item[1])
return (values,ofts)
(['VALUE1', 'VALUE2'], ['OFFSET1', 'OFFSET2'])
Since you have a list of tuples, instead of:
theValue = list[0].VALUE
theOffset = list[0].OFFSET
You can use:
theValue = list[0][0]
theOffset = list[0][1]
So in your for-loop:
def printList(list):
for item in list:
print('VALUE: {}'.format(item[0]))
print('OFFSET: {}'.format(item[1]))
If you want to get all values in list and offsets in a separate list, you can use list-comprehension:
values = [x[0] for x in list]
offsets = [x[1] for x in list]
One more important thing, AVOID using built-in functions like list as variables, use something else instead.
Try using a list comprehension
theValue = [value[0] for value in my_list]
theOffset = [offset[0] for value in offset]
I think namedtuple can help you.
from collections import namedtuple
Element = namedtuple("Element", ["value", "offset"])
element_list = []
for value, offset in my_list:
element_list.append(Element(value, offset))
for element in element_list:
print element.value, element.offset
If you want to get all values and offsets separately, you can use numpy to transform my_list to numpy.array which is a 2d array.
import numpy as np
2d_array = np.array(my_list)
values = 2d_array[:, 0]
offsets = 2d_array[:, 1]
I just want to get those with the index that is a multiple of two
code=[1,2,4,7,2,6,8]
ncode=[code[i] for i%2==0]
Just use this indexing method:
code[::2]
If you want the odd index
code[1::2]
Generally, this is how it works:
seq = L[start:stop:step]
seq = L[::2] # get every other item, starting with the first
seq = L[1::2] # get every other item, starting with the second
You can use list comprehensions this way :
code=[1,2,4,7,2,6,8]
print [val for i,val in enumerate(code) if i%2==0]
enumerate() returns the index and value at the index, which is stored in i and value respectively.
For more details:
list comprehension
enumerate
code = [1,2,4,7,2,6,8]
new_code = []
for i in range(0, len(code), 2): ### iterate over even indexes
new_code.append(code[i])
print new_code
seen = []
dups = collections.defaultdict(list)
for i, item in enumerate(prules)
for j, orig in enumerate(seen):
if item == orig:
dups[j].append(i)
break
else:
seen.append(item)
deleteindex = [val for key,val in dups.iteritems() if seen[key] == '159']
for i in range(o,len(deleteindex)):
n = deleteindex[i]
del rulelines[n]
The above is my code.
What I want to do is to create an array deleteindex which takes in the indice of any item with 159 in.
It does get all the values I want i.e all the indices with the value 159 but when I try to delete the values from a different array with the indices, it returns the error
list indices must be integers, not list.
prules is the array I want to get the index values contains strings of numbers
rulelines contains is a list of strings which I want to use the values taken from prules and use the values as indexes to delete those values in rulelines
Where have I gone wrong?
I'm guessing its something at
deleteindex = [val for key,val in dups.iteritems() if seen[key] == '159']
You are right.
The error is because, in
deleteindex = [val for key,val in dups.iteritems() if seen[key] == '159']
key is a list. As dups is defaultdict(list), the value will always be a list.
This can be verified by:
...
print dict(dups.iteritems()) # adding this
deleteindex = [val for key,val in dups.iteritems() if seen[key] == '159']
...
As for your algorithm, try this, an easier to understand version.
import random
prules = [random.randint(150,156) for i in range(30)]
def get_indexes(li):
retval = {}
for i, x in enumerate(li):
if x not in retval:
retval[x] = []
retval[x].append(i)
return retval
dups = get_indexes(prules)
indexes = dups.get('156',[])
rulelines = [rulelines[i] for i in range(len(rulelines[:])) if i not in indexes]
To get the indexes, just do:
dups.get('156',[])
Which will return a list of indexes if dups['156'] exists, else it returns an empty list.
Your intuition is right.
deleteindex = [val for key,val in dups.iteritems() if seen[key] == '159']
Here each val is one of the values in the dups dictionary you've been populating in the above loop. But what are these values? Well, dups = collections.defaultdict(list) would indicate that each one of these values is a list.
Therefore this code breaks due to your not keeping track of your types:
n = deleteindex[i] # n is a list
del rulelines[n] # you can't index a list with a list
From what I can tell, prules is a list, or a collection at least that can be enumerated, in which case, you can possibly convert it to a set which is all you need to do to remove duplicates.
However, if this is not the case (I can not tell since you have not provided that segment of code) then you could go about the whole thing in a better way:
seen = []
duplicate_indexes = []
for index, item in enumerate(prules):
if item in seen:
del rulelines[index]
else:
seen.append(item)
From your updated Question, I think that you are trying to do something else than what it seems your question is about. I think you are trying to delete every index in rulelines where the corresponding index in prules has a value of '159' if this is the case:
for ix, pr in enumerate(prules):
if pr == '159':
del rulelines[ix]
I have a hunch that I need to access an item in a list (of strings), modify that item (as a string), and put it back in the list in the same index
I'm having difficulty getting an item back into the same index
for item in list:
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[item] = item
print item
now I get an error
TypeError: list indices must be integers, not str
due to this line list[item] = item
which makes sense! but I do not know how to put the item back into the list at that same index using python
what is the syntax for this? Ideally the for loop can keep track of the index I am currently at
You could do this:
for idx, item in enumerate(list):
if 'foo' in item:
item = replace_all(...)
list[idx] = item
You need to use the enumerate function: python docs
for place, item in enumerate(list):
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[place] = item
print item
Also, it's a bad idea to use the word list as a variable, due to it being a reserved word in python.
Since you had problems with enumerate, an alternative from the itertools library:
for place, item in itertools.zip(itertools.count(0), list):
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[place] = item
print item
A common idiom to change every element of a list looks like this:
for i in range(len(L)):
item = L[i]
# ... compute some result based on item ...
L[i] = result
This can be rewritten using enumerate() as:
for i, item in enumerate(L):
# ... compute some result based on item ...
L[i] = result
See enumerate.
For Python 3:
ListOfStrings = []
ListOfStrings.append('foo')
ListOfStrings.append('oof')
for idx, item in enumerate(ListOfStrings):
if 'foo' in item:
ListOfStrings[idx] = "bar"