Remove wildcard string from list - python

I have a list which is a large recurring dataset with headers of the form:
array = ['header = 1','0','1','2',...,'header = 1','1','2','3',...,'header = 2','1','2','3']
The header string can vary between each individual dataset, but the size of the individual datasets do not.
I would like to remove all of the headers so that I am left with:
array = ['0','1','2',...,'1','2','3',...,'1','2','3']
If the header string does not vary, then I can remove them with:
lookup = array[0]
while True:
try:
array.remove(lookup)
except ValueError:
break
However, if the header strings do change, then they are not caught, and I am left with:
array = ['0','1','2',...,'1','2','3',...,'header = 2','1','2','3']
Is there a way in which the sub-string "header" can be removed, regardless of what else is in the string?

Best use a list comprehension with a condition instead of repeatedly removing elements. Also, use startswith instead of using a fixed lookup to compare to.
>>> array = ['header = 1','0','1','2','header = 1','1','2','3','header = 2','1','2','3']
>>> [x for x in array if not x.startswith("header")]
['0', '1', '2', '1', '2', '3', '1', '2', '3']
Note that this does not modify the existing list but create a new one, but it should be considerably faster as each single remove has O(n) complexity.
If you do not know what the header string is, you can still determine it from the first element:
>>> lookup = array[0].split()[0] # use first part before space
>>> [x for x in array if not x.startswith(lookup)]
['0', '1', '2', '1', '2', '3', '1', '2', '3']

Using the find() method you can determine whether or not the word "header" is contained in the first list item and use that to determine whether or not to remove the first item.

Related

Filtering using a str array

I am trying to filter an ASCII list (which contains ASCII and other characters) by using an array that I have created. I am trying to remove any integer string within the list.
import pandas as pd
with open('ASCII.txt') as f:
data = f.read().replace('\t', ',')
print(data, file=open('my_file.csv', 'w'))
df = list(data)
test = ['0','1','2','3','4','5','6','7','8','9']
for x in df:
try:
df = int(df)
for i in range(0,9):
while any(test) in df:
df.remove('i')
print(df)
except:
continue
print(df)
This is what I currently have however, it does not work and outputs:
['3', '3', ',', '0', '4', '1', ',', '2', '1', ',', '!', ',', '\n', '3', '4', ',', '0', '4', ...]
Your if condition for numbers is broken.
any checks if at least one element in the passed iterable is truthy, i.e. not an empty string in your case.
test = ['0','1','2','3','4','5','6','7','8','9']
while any(test) in df: # Condition always evaluates to False
df.remove('i') # Only removes the character 'i' from df
So your condition any(test) evaluates to True. And now you are checking if True is in df which it isn't, so the condition evaluates to False.
The next error is, that you try to remove the letter 'i' from your list with the remove call. This can be fixed by casting the integer to a string
for i in range(9):
# Cast integer to str
while str(i) in df:
# Remove str i from df
df.remove(str(i))
Using a str list instead of the range function, you can directly iterate over the elements of the test list:
df = list(data)
test = ['0','1','2','3','4','5','6','7','8','9']
for num in test:
# Loop as long as num appears in df
while num in df:
df.remove(num) # removes all elements with value of num
By doing so you have to run a second loop to remove all appearances of the current num in df, as remove only removes the first occurrence of that value.
Alternatively you can also check each element of df if it is a digit by using the str method isdigit. But as you modify the list in-place you need to iterate over a copy. Otherwise you'll encounter side-effects as you reduce the size of df:
# Use slice to create a copy of df
for el in df[:]:
if el.isdigit():
df.remove(el)
As you iterate over each element in df you don't need an inner loop to remove each occurrence of value el.

Delete even indexes out of range [duplicate]

I'm trying to remove the odd-indexed elements from my list (where zero is considered even) but removing them this way won't work because it throws off the index values.
lst = ['712490959', '2', '623726061', '2', '552157404', '2', '1285252944', '2', '1130181076', '2', '552157404', '3', '545600725', '0']
def remove_odd_elements(lst):
i=0
for element in lst:
if i % 2 == 0:
pass
else:
lst.remove(element)
i = i + 1
How can I iterate over my list and cleanly remove those odd-indexed elements?
You can delete all odd items in one go using a slice:
del lst[1::2]
Demo:
>>> lst = ['712490959', '2', '623726061', '2', '552157404', '2', '1285252944', '2', '1130181076', '2', '552157404', '3', '545600725', '0']
>>> del lst[1::2]
>>> lst
['712490959', '623726061', '552157404', '1285252944', '1130181076', '552157404', '545600725']
You cannot delete elements from a list while you iterate over it, because the list iterator doesn't adjust as you delete items. See Loop "Forgets" to Remove Some Items what happens when you try.
An alternative would be to build a new list object to replace the old, using a list comprehension with enumerate() providing the indices:
lst = [v for i, v in enumerate(lst) if i % 2 == 0]
This keeps the even elements, rather than remove the odd elements.
Since you want to eliminate odd items and keep the even ones , you can use a filter as follows :
>>>filtered_lst=list(filter(lambda x : x % 2 ==0 , lst))
this approach has the overhead of creating a new list.

Python list insert with index

I have an empty python list. and I have for loop that insert elements with index but at random (means indices are chosen randomly to insert the item). I tried a simple example, with randomly select indices, but it works in some indices but others won't work. Below is a simple example of what I wanna do:
a=[]
#a=[]
a.insert(2, '2')
a.insert(5, '5')
a.insert(0, '0')
a.insert(3, '3')
a.insert(1, '1')
a.insert(4, '4')
The output of this is a = ['0','1','2','5','4','3']
it's correct in the first three (0,1,2) but wrong in the last three ('5','4','3')
How to control insert to an empty list with random indices.
list.insert(i, e) will insert the element e before the index i, so e.g. for an empty list it will insert it as the first element.
Map out the operations in your head using this information:
a = [] # []
a.insert(2, '2') # ['2']
a.insert(5, '5') # ['2', '5']
a.insert(0, '0') # ['0', '2', '5']
a.insert(3, '3') # ['0', '2', '5', '3']
a.insert(1, '1') # ['0', '1', '2', '5', '3']
a.insert(4, '4') # ['0', '1', '2', '5', '4', '3']
Keep in mind that lists are not fixed sized arrays. The list has no predefined size, and can grow and shrink by appending or popping elements.
For what you might want to do you can create a list and use indexing to set the values.
If you know the target size (e.g. it is 6):
a = [None] * 6
a[2] = '2'
# ...
If you only know the maximum possible index, it would have to be done like this:
a = [None] * (max_index+1)
a[2] = '2'
# ...
a = [e for e in a if e is not None] # get rid of the Nones, but maintain ordering
If you do not know the maximum possible index, or it is very large, a list is the wrong data structure, and you could use a dict, like pointed out and shown in the other answers.
If your values are unique, could you use them as keys in a dictionary, with the dict values being the index?
a={}
nums = [1,4,5,7,8,3]
for num in nums:
a.update({str(num): num})
sorted(a, key=a.get)
If you have an empty array and you try to add some element in the third position, that element will be added in first position. Because python's list is a linked list.
You could resolve your problem creating a list with None values in it. This could be made with this:
# Creating a list with size = 10, so you could insert up to 10 elements.
a = [None] * 10
# Inserting the 99 in third position
a.insert(3,99)
Another way to do that is using numpy:
import numpy as np
# Create an empty array with 10 elements
a = np.empty(10,dtype=object)
# Insert 99 number in third position
np.insert(a, 3, 99)
print(a)
# array([None, None, None, 99, None, None, None, None, None, None, None],
# dtype=object)

Python set anomaly

I'm trying to understand how sets work when I try to get values from a list.
So when I run the code at the bottom
wordlist = ['hello',1,2,3]
wordSet = set(wordlist)
Output is
{3, 1, 2, 'hello'}
or something similar because set doesn't have a order.
But my point is, when I try to reach my list's first element, like using myList[0] when using it's value to create a set
wordlist = ['hello',1,2,3]
wordSet = set(wordlist[0])
I was expecting output to be
{'hello'}
but instead, I get
{'l', 'o', 'h', 'e'}
or one of randomized style.
My point is when I put my list in set function directly, it uses entire list to create a set, but when I want to create a set with using only first element in my list, it divides my string to characters.
Why does that happen ?
Strings such as 'hello' are iterable; set() converts iterables into sets.
To clarify,
set(('1', '1', '2', '3')) == {'1', '2', '3'}
set(['1', '1', '2', '3']) == {'1', '2', '3'}
set('1123') == {'1', '2', '3'}
Calling set on an object will iterate the object. Strings are iterable, yielding individual characters. If you want a set containing only the first element of wordlist, you would need to use an iterable which only contains that element:
set([worldlist[0]])
Or, more directly, just use the curly braces:
{worldlist[0]}

How to remove specific strings from a list

From the following list how can I remove elements ending with Text.
My expected result is a=['1,2,3,4']
My List is a=['1,2,3,4,5Text,6Text']
Should i use endswith to go about this problem?
Split on commas, then filter on strings that are only digits:
a = [','.join(v for v in a[0].split(',') if v.isdigit())]
Demo:
>>> a=['1,2,3,4,5Text,6Text']
>>> [','.join(v for v in a[0].split(',') if v.isdigit())]
['1,2,3,4']
It looks as if you really wanted to work with lists of more than one element though, at which point you could just filter:
a = ['1', '2', '3', '4', '5Text', '6Text']
a = filter(str.isdigit, a)
or, using a list comprehension (more suitable for Python 3 too):
a = ['1', '2', '3', '4', '5Text', '6Text']
a = [v for v in a if v.isdigit()]
Use str.endswith to filter out such items:
>>> a = ['1,2,3,4,5Text,6Text']
>>> [','.join(x for x in a[0].split(',') if not x.endswith('Text'))]
['1,2,3,4']
Here str.split splits the string at ',' and returns a list:
>>> a[0].split(',')
['1', '2', '3', '4', '5Text', '6Text']
Now filter out items from this list and then join them back using str.join.
try this. This works with every text you have in the end.
a=['1,2,3,4,5Text,6Text']
a = a[0].split(',')
li = []
for v in a:
try : li.append(int(v))
except : pass
print li

Categories

Resources