Create a list with string + range - python

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)

Related

Iterating 2 lists to form a dictionary with unique key but multiple items

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)

Python, sort with key

I am having trouble understanding key parameter in sorted function in Python.
Let us say, the following list is given: sample_list = ['Date ', 'of', 'birth', 'year 1990', 'month 10', 'day 15'] and I would like to sort only the strings that contain number.
Expected output: ['Date ', 'of', 'birth', 'month 10', 'day 15', 'year 1990']
Until now, I only managed to print the string with the number
def sort_with_key(element_of_list):
if re.search('\d+', element_of_list):
print(element_of_list)
return element_of_list
sorted(sample_list, key = sort_with_key)
But how do I actually sort those elements?
Thank you!
We can try sorting with a lambda:
sample_list = ['Date ', 'of', 'birth', 'year 1990', 'month 10', 'day 15']
sample_list = sorted(sample_list, key=lambda x: int(re.findall(r'\d+', x)[0]) if re.search(r'\d+', x) else 0)
print(sample_list)
This prints:
['Date ', 'of', 'birth', 'month 10', 'day 15', 'year 1990']
The logic used in the lambda is to sort by the number in each list entry, if the entry has a number. Otherwise, it assigns a value of zero to other entries, placing them first in the sort.
If I understand correctly, you want strings with a number to be sorted with this number as key, and strings without a number to be at the beginning?
You need a key that extracts the number from the string. We can use str.isdigit() to extract digits from a string, ''.join() to put these digits back together, and int() to convert to an integer. If there are no digits in the string, we'll return -1 instead, so it comes before all nonnegative numbers.
sample_list = ['Date ', 'of', 'birth', 'year 1990', 'month 10', 'day 15', 'answer 42', 'small number 0', 'large number 8676965', 'no number here']
sample_list.sort(key=lambda s: int(''.join(c for c in s if c.isdigit()) or -1))
print(sample_list)
# ['Date ', 'of', 'birth', 'no number here', 'small number 0', 'month 10', 'day 15', 'answer 42', 'year 1990', 'large number 8676965']

Working with nested loops in python by keeping the inner list element as it is

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)

Sort dictionary by key alphabetically [duplicate]

This question already has answers here:
How do I sort a dictionary by key?
(32 answers)
Closed 5 years ago.
I'm having trouble sorting my dictionary alphabetically by its keys.
Here's my code:
colorSizes = {'Rust': ['SIZE 8', 'SIZE 10', 'SIZE 12', 'SIZE 14', 'SIZE 16', 'SIZE 18'],
'Middle Blue': ['SIZE 8', 'SIZE 10', 'SIZE 12', 'SIZE 14', 'SIZE 16', 'SIZE 18'],
'Grey': ['SIZE 8', 'SIZE 10', 'SIZE 12', 'SIZE 14', 'SIZE 16', 'SIZE 18'],
'Aqua': ['SIZE 8', 'SIZE 10', 'SIZE 12', 'SIZE 14', 'SIZE 16', 'SIZE 18'],
'Navy': ['SIZE 8', 'SIZE 10', 'SIZE 12', 'SIZE 14', 'SIZE 16']}
realColor = {}
for key in sorted(colorSizes.keys()):
realColor[key] = colorSizes.get(key)
print(realColor)
What I get:
{'Yellow/Fuschia':['Large', 'Extra Large'],
'Black':['Small', 'Medium', 'Large']}
What I wanna get:
{'Black':['Small', 'Medium', 'Large'], 'Yellow/Fuschia':['Large', 'Extra Large']}
Thanks!
Dictionaries in python versions < 3.6 are unordered, sorting and reinserting is meaningless.
As a fix, either
Switch to python3.6 (keep in mind the caveats), or
Use an OrderedDict
For the second option, replace realColor = {} with a collections.OrderedDict:
from collections import OrderedDict
realColor = OrderedDict()
Here's an example of how an OrderedDict remembers the order of insertion:
dict1 = {}
dict1['k'] = 1
dict1['aSDFDF'] = 1234
print(dict1) # {'aSDFDF': 1234, 'k': 1}
from collections import OrderedDict
dict2 = OrderedDict()
dict2['k'] = 1
dict2['aSDFDF'] = 1234
print(dict2) # OrderedDict([('k', 1), ('aSDFDF', 1234)])
The __repr__ might be different, but the latter is still a dictionary and can be used accordingly.

How to print part of item in a list? [closed]

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

Categories

Resources