Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a list that looks like this:
['Blake 4', 'Bolt 1', 'De Grasse 3', 'Gatlin 2', 'Simbine 5', 'Youssef Meite 6']
I am trying to print this:
Blake
Bolt
De Grasse
Gatlin
Simbine
Youssef Meite
How do I go about writing a list comprehension that handles this scenario? I tried using split and indexing but nothing I have used has worked.
Assuming all the values keep that pattern, split and join back, ignoring last value in splitted array:
l = ['Blake 4', 'Bolt 1', 'De Grasse 3', 'Gatlin 2', 'Simbine 5', 'Youssef Meite 6']
for x in l:
print(' '.join(x.split()[:-1]))
Otherwise, use regex to eliminate numerals:
import re
l = ['Blake 4', 'Bolt 1', 'De Grasse 3', 'Gatlin 2', 'Simbine 5', 'Youssef Meite 6']
for x in l:
print(re.sub(' \d+', '', x))
list comprehension is useless to print stuff (or any operations where you don't need the return value).
In your case, you could use str.rpartition in a loop to print only the left hand of the rightmost space found in the string:
l =['Blake 4', 'Bolt 1', 'De Grasse 3', 'Gatlin 2', 'Simbine 5', 'Youssef Meite 6']
for s in l:
print(s.rpartition(" ")[0])
Just stripping the last digit off the list would be a good usage of listcomp:
newl = [s.rpartition(" ")[0] for s in l]
Try this:
l = ['Blake 4', 'Bolt 1', 'De Grasse 3', 'Gatlin 2', 'Simbine 5', 'Youssef Meite 6']
for i in l:
print(i[:-2])
Indexing is sufficient for solving your problem.
Based on #Jean-François 's comment, if you are trying to remove all the characters before the last space, you can do this instead:
l = ['Blake 4', 'Bolt 1', 'De Grasse 3', 'Gatlin 2', 'Simbine 5', 'Youssef Meite 6']
for i in l:
print(i[:-i[::-1].index(' ')-1])
Related
I've got 2 lists, one with plate numbers that has duplicates in it, and the other with corresponding groups that each plate belongs to. Duplicated number means that the plate belongs to several groups. I'm trying to make a dict with the following output:
L1 = ['173', '607', '607', '581', '522', '522']
L2 = ['fleet 6', 'fleet 4', 'fleet 6', 'Toyota', 'Maintenance', 'fleet 1']
# Desirable output
# '173': 'fleet 6'
# '607': ['fleet4', 'fleet6']
# '581': 'Toyota'
# '522': ['Maintenance', 'fleet 1']
I have no clue how to cluster values as lists from L2 to match with duplicates from L1, along with singles, any ideas please?
Try this approach to see if that help. It's only one way to solve it, prob. easy to understand.
from collections import defaultdict
from pprint import pprint
L1 = ['173', '607', '607', '581', '522', '522']
L2 = ['fleet 6', 'fleet 4', 'fleet 6', 'Toyota', 'Maintenance', 'fleet 1']
# Desirable output
# '173': 'fleet 6'
# '607': ['fleet4', 'fleet6']
# '581': 'Toyota'
# '522': ['Maintenance', 'fleet 1']
dc = defaultdict(list)
for i in range(len(L1)):
item = L1[i]
dc[item].append(L2[i])
pprint(dc)
Edit:
As #KellyBundy suggests, you could use this more pythonic way to solve it too:
dc = defaultdict(list)
for item, plate in zip(L1, L2):
dc[item].append(plate)
pprint(dc)
Try the following:
d = {}
L1 = ['173', '607', '607', '581', '522', '522']
L2 = ['fleet 6', 'fleet 4', 'fleet 6', 'Toyota', 'Maintenance', 'fleet 1']
for l1, l2 in zip(L1, L2):
d[l1] = d.get(l1, [])
d[l1].append(l2)
Where the d.get() function gets the item and if the key does not exist returns an empty list
Using setdefault:
d = {}
for k, v in zip(L1, L2):
d.setdefault(k, []).append(v)
print(d)
#{'173': ['fleet 6'], '607': ['fleet 4', 'fleet 6'], '581': ['Toyota'], '522': ['Maintenance', 'fleet 1']}
You can make this:
result = {key: [] for key in L1}
for i, value in enumerate(L2):
result[L1[i]].append(value)
Simple and quick!
Steps
Create and dict with all keys of L1 and an empty list in value
Add the value of L2 (know the key by the index on enumerate)
I need your help:
I want to create a list looking like this ['Unnamed: 16', 'Unnamed: 17', 'Unnamed:18'] for a range (16,60). How can I proceed?
I don't know if my question is clear but it's like doing list(range(16, 60) but with a string before each numbers.
Thank you very much for your help!!
You can use f-strings to do so :
my_list = [f"Unnamed: {i}" for i in range(16, 60)]
# Output
['Unnamed: 16', 'Unnamed: 17', 'Unnamed: 18', 'Unnamed: 19', ...]
I would do it following way
prefix = "Unnamed: "
lst = [prefix + str(i) for i in range(16,25)]
print(lst)
output
['Unnamed: 16', 'Unnamed: 17', 'Unnamed: 18', 'Unnamed: 19', 'Unnamed: 20', 'Unnamed: 21', 'Unnamed: 22', 'Unnamed: 23', 'Unnamed: 24']
Note: I used othre range for brevity sake. You might elect to use one of string formatting method instead.
You can do it using map as,
list(map(lambda x: f'Unnamed: {x}', range(16, 60)))
You can use f strings
name = 'Unamed:'
list = [f"{prefix} {i}" for i in range(16, 60)]
print(list)
my_list = []
for i in range(16, 60):
my_list.append("Unnamed: " + str(i))
print(my_list)
I have a nested loop that follows as below
arr = [[' item 1 ', 'item 2 ', 'item 3'], ['item 4 ', 'item 5', 'item 6'], ['item 7 ', 'item 8', 'item 9' ]]
I am trying to loop through the arr with 2 for loops to get rid of (strip) the spaces around each item in the inner loop. But when I use the following code, although I can get rid of the spaces, the final result only forms a combined list without the inner list elements intact.
clean_arr = []
for i in arr:
for j in i:
clean_arr.append(j.strip(' '))
The result I get is a single list without any inner lists/nested lists. But what I want is to keep the exact nested structure.
How can I achieve the result? Could you please put some discussion as well. Thanks
Try a list comprehension as follows:
clean_arr = [[y.strip() for y in x] for x in arr]
print(clean_arr)
Output:
[['item 1', 'item 2', 'item 3'], ['item 4', 'item 5', 'item 6'], ['item 7', 'item 8', 'item 9']]
If you want to use a for loop, try the below code:
clean_arr = []
for i in arr:
l = []
for j in i:
l.append(j.strip())
clean_arr.append(l)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an array that contains numbers and characters, e.g. ['A 3', 'C 1', 'B 2'], and I want to sort it using the numbers in each element.
I tried the below code but it did not work
def getKey(item):
item.split(' ')
return item[1]
x = ['A 3', 'C 1', 'B 2']
print sorted(x, key=getKey(x))
To be safe, I'd recommend you to strip everything but the digits.
>>> import re
>>> x = ['A 3', 'C 1', 'B 2', 'E']
>>> print sorted(x, key=lambda n: int(re.sub(r'\D', '', n) or 0))
['E', 'C 1', 'B 2', 'A 3']
With your method;
def getKey(item):
return int(re.sub(r'\D', '', item) or 0)
>>> print sorted(x, key=getKey)
['E', 'C 1', 'B 2', 'A 3']
What you have, plus comments to what's not working :P
def getKey(item):
item.split(' ') #without assigning to anything? This doesn't change item.
#Also, split() splits by whitespace naturally.
return item[1] #returns a string, which will not sort correctly
x = ['A 3', 'C 1', 'B 2']
print sorted(x, key=getKey(x)) #you are assign key to the result of getKey(x), which is nonsensical.
What it should be
print sorted(x, key=lambda i: int(i.split()[1]))
This is one way to do it:
>>> x = ['A 3', 'C 1', 'B 2']
>>> y = [i[::-1] for i in sorted(x)]
>>> y.sort()
>>> y = [i[::-1] for i in y]
>>> y
['C 1', 'B 2', 'A 3']
>>>
Given the list puzzle above, I need to be able to swap the position of X to left, right, top or bottom. The question is, how do I swap it with the item beside or in the other list in the list puzzle?
puzzle = [[' 1', ' 2', ' 3', ' 4'],
[' 5', ' 6', ' 7', ' 8'],
[' 9', '10', '11', '12'],
['13', '14', '15', ' X']]
#generic swap puzzle[a][b] with puzzle[c][d]
puzzle[a][b], puzzle[c][d] = puzzle[c][d], puzzle[a][b]