python remove alphanum and numbers elements in a list [duplicate] - python

This question already has answers here:
Remove all items in Python list containing a number [duplicate]
(2 answers)
Remove strings from a list that contains numbers in python [duplicate]
(6 answers)
Check if a string contains a number
(20 answers)
Closed 4 years ago.
How do I remove alphanum and numbers elements in a list? Below code is not removing, what am I doing wrong here? After research in other stackoverflow, they are removing characters but not the elements itself.
ls = ['1a', 'b3', '1.45','apples','oranges','mangoes']
cleaned = [x for x in ls if x is not x.isalnum() or x is not x.isdigit()]
cleaned
result = re.sub(r'[^a-zA-Z]', "", ls)
print(result) #expected string or bytes-like object
output should be:
['apples','oranges','mangoes']
enter code here

Try this:
ls = ['1a', 'b3', '1.45','apples','oranges','mangoes']
[l for l in ls if l.isalpha()]
Output:
['apples', 'oranges', 'mangoes']

try this:-
ls = ['1a', 'b3', '1.45','apples','oranges','mangoes']
l = []
for i in ls:
if not bool(re.search(r'\d', i)):
l.append(i)
print(l)

I'd do it like this:
newList = []
for x in ls:
if x.isalpha():
newList.append(x)
print(newList)
It works for me. It only adds the element to the new list if they don't contain a number.

Related

list of lists coordinates to a list of coordinates with space for SVG file [duplicate]

This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Apply function to each element of a list
(4 answers)
Closed 3 months ago.
I have a list
my_list = [[200.0, 10.0], [250.0, 190.0], [160.0, 210.0]]
I want get the list of these coordinate with space between them
req_list = "200,10 250,190 160,210"
to write these in SVG format for polygons.
I tried replacing "[]" with " " but replace doesn't work for an array
my_list.replace("[", " ")
You can iterate through the list and append them into an empty string defined, for example:
req_list = ""
for cor in my_list:
req_list += '{},{} '.format(int(cor[0]),int(cor[1]))
print(req_list[:-1])
Prints:
200,10 250,190 160,210
Indexed till -1 is to ignore the last white space.
You can use str.join to the sublists:
my_list = [[200.0, 10.0], [250.0, 190.0], [160.0, 210.0]]
req_list = " ".join(",".join(f"{int(v)}" for v in l) for l in my_list)
print(req_list)
Prints:
200,10 250,190 160,210

How to generate all possible combinations from the letters of strings in a list [duplicate]

This question already has answers here:
Generating all possible combinations of characters in a string
(5 answers)
Algorithm for generating all string combinations
(3 answers)
Closed 10 months ago.
I was trying to generate all possible combinations from the letters of strings in a list.
For example:
Input: ['jkl', 'ghi', 'def']
Output: ["jgd", "jge", "jgf", "jhd", "jhe", "jhf", "jid", "jie", "jif"...]
lst = ['jkl', 'ghi', 'def']
import itertools
list(map("".join, itertools.product(*lst)))
# result:
['jgd',
'jge',
'jgf',
'jhd',
'jhe',
'jhf',
'jid',
'jie',
'jif',
'kgd',
'kge',
'kgf',
'khd',
'khe',
'khf',
'kid',
'kie',
'kif',
'lgd',
'lge',
'lgf',
'lhd',
'lhe',
'lhf',
'lid',
'lie',
'lif']
I can propose you a trivial algorithm to do the same, it is using recursion:
def associations(entry):
while len(entry) > 2:
to_treat_later = entry.pop()
print(f"We will treat {to_treat_later} later")
entry = associations(entry)
entry.append(to_treat_later)
else:
print(f"we can start with {entry}")
associated_entry = []
for elt_1 in entry[0]:
for elt_2 in entry[1]:
associated_entry.append(f"{elt_1}{elt_2}")
return [associated_entry]
def convert_entry(entry):
converted_entry = []
for elt in entry:
list_elt = []
for letter in elt:
list_elt.append(letter)
converted_entry.append(list_elt)
return converted_entry
the_entry = ["jkl", "ghi", "def", "cfe"]
associations(convert_entry(the_entry))

removing duplicates by comparing substrings in a list [duplicate]

This question already has answers here:
Removing duplicate characters from a string
(15 answers)
Closed 2 years ago.
I have a list l = ['AAB', 'CAA', 'ADA'] . I want to get the following list without duplicated characters new_l = ['AB','CA','AD']. I am trying to iterate on a nested loop but I'm not sure this is the best way to accomplish this. here is my try:
new_l = []
for i in range(0,len(l)-1):
for j in range(0,len(l)-1):
if l[i][j] != l[i+1][j+1]:
new_l = ..............
Can someone help me on how to get a set by iterating over every element of this list of strings ?
You can easily do it, since a string is also a list.
strl = ['AAB', 'CAA', 'ADA']
new_strl = []
for s in strl:
new_strl.append("".join(set(s)))
print(new_strl)
Set can mess order of characters. Better use OrderedDict:
from collections import OrderedDict
strl = ['AAB', 'CAA', 'ADA']
result = ["".join(OrderedDict.fromkeys(s)) for s in strl]
l = ['AAB', 'CAA', 'ADA']
new_l = [''.join(sorted(set(x))) for x in l]
#op
['AB', 'AC', 'AD']

Nested list in pairs from list [duplicate]

This question already has answers here:
Split by comma and strip whitespace in Python
(10 answers)
Closed 4 years ago.
Input list example = ['listen, silent', 'dog, fog', 'colour, simple']
how do I return a nested list from the example in pairs, to look like this:
[[word1,word2], [word3,word4]...etc]
please, thank you
I have tried list comprehension,
my_list1 = [i[1] for i in my_list]
my_list2 = [i[0] for i in my_list]
but it took out only the first letter instead of word... hoping for it to look like;
[listen, silent],[dog, fog]...etc
You can split each word in the list using , as a separator:
l = ['listen, silent', 'dog, fog', 'colour, simple']
l = [elem.split(', ') for elem in l]
print(l)
Output:
[['listen', 'silent'], ['dog', 'fog'], ['colour', 'simple']]

How do i make this list into a string in python? [duplicate]

This question already has answers here:
Converting a list to a string [duplicate]
(8 answers)
How to convert list to string [duplicate]
(3 answers)
Closed 9 years ago.
I am trying, in the following code, to encrypt a message. The problem is that my result comes up in a list format instead of a string. How do I make it into a string?
You need to flatten the nested lists in your result and then turn it into a string. Here's one way to do it:
>>> import itertools
>>> result = [['I', 'R', 'A', ' ', 'O'], [' ', 'E', 'D', 'Y', 'U']]
>>> ''.join(itertools.chain(*result))
'IRA O EDYU'
finalArray is clearly a list:
finalArray = []
To convert it to a string, use join:
print ''.join(finalArray)
But first, you probably do not want these nested lists. You should use extend, not append:
def stringEncrypter(A):
length = len(A)
finalArray = []
if length%2 == 0:
firstArray=[]*(length/2)
secondArray=[]*(length/2)
else:
firstArray=[]*((length+1)/2)
secondArray=[]*((length-1)/2)
for x in range(0, length-1):
if x%2 == 0:
firstArray.append(A[x:x+1])
secondArray.append(A[x+1:x+2])
finalArray.extend(firstArray)
finalArray.extend(secondArray)
print ''.join(finalArray)

Categories

Resources