Nested list in pairs from list [duplicate] - python

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']]

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 compare substring in a list and fetch the whole string if its present using python [duplicate]

This question already has answers here:
How to check if a string is a substring of items in a list of strings
(18 answers)
Pythonic way to print list items
(13 answers)
Closed 6 months ago.
I have a list containing strings
list=["geeks for geeks","string1","string2","geeks"]
I want to check if "geek" is present in the list, if present fetch me the whole string from the list
if geek in list:
output :
geeks for geeks
geeks
how to achieve this?
Sounds like you want a list comprehension.
lst = ["geeks for geeks", "string1", "string2", "geeks"]
lst2 = [s for s in lst if "geek" in s]
# ['geeks for geeks', 'geeks']
You may wish to use str.lower to account for different capitalizations of "geek".
lst2 = [s for s in lst if "geek" in s.lower()]
Please replace the Python reserved word list with another variable name like lis or words. You can try this
lis = ["geeks for geeks", "string1", "string2", "geeks"]
for word in lis:
if "geek" in word:
print(word)
The output is
geeks for geeks
geeks
Or if you want to append to a new list
words = []
for word in lis:
if "geek" in word:
words.append(word)
print(words)
Or using list comprehension (thanks #Chris!)
[word for word in lis if "geek" in word]
The output is a list
['geeks for geeks', 'geeks']

How to turn each word in a string in a list into elements in a list [duplicate]

This question already has answers here:
extract each word from list of strings
(7 answers)
Closed 1 year ago.
I would like to turn each word in a string in a list into elements in a list
Example:
Input: l = ["the train was late", "I looked for mary and sam at the bus station"]
Output: l = ["the","train","was","late","I","looked","for","mary","and","sam","at","the","bus","station"]
I tried doing this:
l = []
for word in data_txt_file:
s = word.split(" ")
l.append(s)
But then I get:
Output: l = [["the","train","was","late",],["I","looked","for","mary","and","sam","at","the","bus","station"]]
Maybe from here I can just remove the nested lists and flatten it, however, can I just I immediately go there, instead of doing like this middle step with splitting it.
The most simple way to go with the current code itself is to make use of the extend methods provided to lists:
l = []
for word in data_txt_file:
s = word.split(" ")
l.extend(s)
The easy solution would be to transform the first list to a single string, so you can just tokenize it as a whole:
l = ' '.join(data_txt_file).split(' ')
Or, you could just flatten the nested list you got in your solution:
l2 = []
for e in l: l2+=e
This would also result in a list that just has the words as elements.
Or, if you really want to make this word by word as in your first solution:
l = []
for line in data_txt_file:
for word in line.split(' '):
l.append(word)
This can be done in a single line of code:
l = ",".join(l).replace(",", " ").split(" ")
Output: ['the', 'train', 'was', 'late', 'I', 'looked', 'for', 'mary', 'and', 'sam', 'at', 'the', 'bus', 'station']

List of lists middle element extraction in python [duplicate]

This question already has answers here:
How to extract the n-th elements from a list of tuples
(8 answers)
Closed 4 years ago.
I have a list of lists as follows
[('trojan', 'virus', 0.4731800100841465), ('elb', 'Ebola', 0.3722390506633956)]
How to extract only the middle element i.e. 'virus' and 'Ebola' ?
You can use a comprehnesion list
your_list = [('trojan', 'virus', 0.4731800100841465), ('elb', 'Ebola', 0.3722390506633956)]
l = [x[1] for x in your_list]
output:
['virus', 'Ebola']
You have to find middle index
data = [
('trojan', 'virus', 0.4731800100841465),
('elb', 'Ebola', 0.3722390506633956)
]
middle_data = []
for inside_list in data:
middle = len(inside_list)/2
middle_data.append(inside_list[middle])
print(middle_data)
Output: ['virus', 'Ebola']

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

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.

Categories

Resources