How can you erase a particular value in the list?
The value of the list exists.
review_list = ["14hour","16hour","20hour","24hour","8hour","4hour","2hour","hello","jae12"]
If you look at the list value,
Only numeric values change before int(1-24)hour.
How can you remove int (1-24)hour and output the remaining values?
OUTPUT
review_list = "hello","jae12"]
Based on your expected output, you want to remove elements which contain "hour" in the value
review_list = ["14hour","16hour","20hour","24hour","8hour","4hour","2hour","hello","jae12"]
review_filtered = [x for x in review_list if "hour" not in x]
Output
["hello", "jae12"]
review_list = list(filter(lambda item: not item.endswith("hour"), review_list))
or
import re
review_list = list(filter(lambda item: not re.match('^[0-9]+hour$',item), review_list))
Related
I have a list l:
l = ['Abc.xlsx', 'Wqe.csv', 'Abc.csv', 'Xyz.xlsx']
In this list, I need to remove duplicates without considering the extension. The expected output is below.
l = ['Wqe.csv', 'Abc.csv', 'Xyz.xlsx']
I tried:
l = list(set(x.split('.')[0] for x in l))
But getting only unique filenames without extension
How could I achieve it?
You can use a dictionary comprehension that uses the name part as key and the full file name as the value, exploiting the fact that dict keys must be unique:
>>> list({x.split(".")[0]: x for x in l}.values())
['Abc.csv', 'Wqe.csv', 'Xyz.xlsx']
If the file names can be in more sophisticated formats (such as with directory names, or in the foo.bar.xls format) you should use os.path.splitext:
>>> import os
>>> list({os.path.splitext(x)[0]: x for x in l}.values())
['Abc.csv', 'Wqe.csv', 'Xyz.xlsx']
If the order of the end result doesn't matter, we could split each item on the period. We'll regard the first item in the list as the key and then keep the item if the key is unique.
oldList = l
setKeys = set()
l = []
for item in oldList:
itemKey = item.split(".")[0]
if itemKey in setKeys:
pass
else:
setKeys.add(itemKey)
l.append(item)
Try this
l = ['Abc.xlsx', 'Wqe.csv', 'Abc.csv', 'Xyz.xlsx']
for x in l:
name = x.split('.')[0]
find = 0
for index,d in enumerate(l, start=0):
txt = d.split('.')[0]
if name == txt:
find += 1
if find > 1:
l.pop(index)
print(l)
#Selcuk Definitely the best solution, unfortunately I don't have enough reputation to vote you answer.
But I would rather use el[:el.rfind('.')] as my dictionary key than os.path.splitext(x)[0] in order to handle the case where we have sophisticated formats in the name. that will give something like this:
list({x[:x.rfind('.')]: x for x in l}.values())
I have the following list and am wanting to convert it into a dictionary where the 4 digit value at the start of each item becomes the id.
['3574,A+,2021-03-24', '3575,O+,2021-04-03', '3576,AB-,2021-04-09', '3580,AB+,2021-04-27', '3589,A+,2021-05-08', '3590,B-,2021-05-11']
I have tried many different methods but it doesn't seem to work.
You can use str.split, map and dictionary comprehension
# data holds the list you have provided
{splitted[0]:splitted[1:] for splitted in map(lambda item:item.split(','), data)}
OUTPUT:
Out[35]:
{'3574': ['A+', '2021-03-24'],
'3575': ['O+', '2021-04-03'],
'3576': ['AB-', '2021-04-09'],
'3580': ['AB+', '2021-04-27'],
'3589': ['A+', '2021-05-08'],
'3590': ['B-', '2021-05-11']}
You can use dictionary comprehension with str.split:
lst = [
"3574,A+,2021-03-24",
"3575,O+,2021-04-03",
"3576,AB-,2021-04-09",
"3580,AB+,2021-04-27",
"3589,A+,2021-05-08",
"3590,B-,2021-05-11",
]
out = {int(v.split(",")[0]): v.split(",")[1:] for v in lst}
print(out)
Prints:
{
3574: ["A+", "2021-03-24"],
3575: ["O+", "2021-04-03"],
3576: ["AB-", "2021-04-09"],
3580: ["AB+", "2021-04-27"],
3589: ["A+", "2021-05-08"],
3590: ["B-", "2021-05-11"],
}
Here is the code to do what I believe you asked for. I have also added comments in the code for a bit more clarification.
my_list = ['3574,A+,2021-03-24',
'3575,O+,2021-04-03',
'3576,AB-,2021-04-09',
'3580,AB+,2021-04-27',
'3589,A+,2021-05-08',
'3590,B-,2021-05-11']#your list
my_dict = {}#The dictionary you want to put the list into
print("Your list:", my_list, "\n")
for item in my_list:#cycles through every item in your list
ID, value = item.split(",", 1)#Splits the item in your list only once (when it sees the first comma)
print(ID + ": " + value)
my_dict[ID] = value#Add the ID and value to your dictionary
print("\n" + "Your desired dictionary:", my_dict)
Which outputs this:
Your list: ['3574,A+,2021-03-24', '3575,O+,2021-04-03', '3576,AB-,2021-04-09', '3580,AB+,2021-04-27', '3589,A+,2021-05-08', '3590,B-,2021-05-11']
3574: A+,2021-03-24
3575: O+,2021-04-03
3576: AB-,2021-04-09
3580: AB+,2021-04-27
3589: A+,2021-05-08
3590: B-,2021-05-11
Your desired dictionary: {'3574': 'A+,2021-03-24', '3575': 'O+,2021-04-03', '3576': 'AB-,2021-04-09', '3580': 'AB+,2021-04-27', '3589': 'A+,2021-05-08', '3590': 'B-,2021-05-11'}
Enjoy!
TRY:
result = dict(i.split(',', 1) for i in lst)
OUTPUT:
{'3574': 'A+,2021-03-24',
'3575': 'O+,2021-04-03',
'3576': 'AB-,2021-04-09',
'3580': 'AB+,2021-04-27',
'3589': 'A+,2021-05-08',
'3590': 'B-,2021-05-11'}
I am trying to replace the valuse in a list with the long format name.
value_list = ['Gi1/0/8', 'Gi1/0/31', 'Gi1/0/32', 'Gi1/0/33', 'Gi1/0/34', 'Gi1/0/23', 'Gi1/0/27']
I am running the following script:
for value in value_list:
value = re.sub(r'Gi', 'GigabitEthernet', value)
print value
print value_list
This is my out put:
GigabitEthernet1/0/8
GigabitEthernet1/0/31
GigabitEthernet1/0/32
GigabitEthernet1/0/33
GigabitEthernet1/0/34
GigabitEthernet1/0/23
GigabitEthernet1/0/27
I just need to change the values in the list, it seems doing it all wrong. Can anyone help me do this in an efficient manner so i dont need to create another list from the individual outputs??
Then use list comprehension instead:
print([re.sub(r'Gi', 'GigabitEthernet', value) for value in value_list])
Output:
['GigabitEthernet1/0/8', 'GigabitEthernet1/0/31', 'GigabitEthernet1/0/32', 'GigabitEthernet1/0/33', 'GigabitEthernet1/0/34', 'GigabitEthernet1/0/23', 'GigabitEthernet1/0/27']
This code updates existing list:
value_list = ['Gi1/0/8', 'Gi1/0/31', 'Gi1/0/32', 'Gi1/0/33', 'Gi1/0/34', 'Gi1/0/23', 'Gi1/0/27']
for i in range(len(value_list)):
value_list[i] = re.sub(r'Gi', 'GigabitEthernet', value_list[i])
print value_list
# ['GigabitEthernet1/0/8', 'GigabitEthernet1/0/31', 'GigabitEthernet1/0/32', 'GigabitEthernet1/0/33', 'GigabitEthernet1/0/34', 'GigabitEthernet1/0/23', 'GigabitEthernet1/0/27']
Using map
Ex:
import re
value_list = ['Gi1/0/8', 'Gi1/0/31', 'Gi1/0/32', 'Gi1/0/33', 'Gi1/0/34', 'Gi1/0/23', 'Gi1/0/27']
value_list = list(map(lambda value: re.sub(r'Gi', 'GigabitEthernet', value), value_list))
print(value_list)
Output:
['GigabitEthernet1/0/8', 'GigabitEthernet1/0/31', 'GigabitEthernet1/0/32', 'GigabitEthernet1/0/33', 'GigabitEthernet1/0/34', 'GigabitEthernet1/0/23', 'GigabitEthernet1/0/27']
To change the list "in-place" you need to set each item in the list to the new value. Just doing value = re.sub(r'Gi', 'GigabitEthernet', item) doesn't change the value stored in the list.
This code changes the values in the list:
>>> value_list = ['Gi1/0/8', 'Gi1/0/31', 'Gi1/0/32', 'Gi1/0/33', 'Gi1/0/34', 'Gi1/0/23', 'Gi1/0/27']
>>> for idx, item in enumerate(value_list):
... value_list[idx] = re.sub(r'Gi', 'GigabitEthernet', item)
...
>>> value_list
['GigabitEthernet1/0/8', 'GigabitEthernet1/0/31', 'GigabitEthernet1/0/32', 'GigabitEthernet1/0/33', 'GigabitEthernet1/0/34', 'GigabitEthernet1/0/23', 'GigabitEthernet1/0/27']
The enumerate function generates the list indexes for you, so you can iterate over your list pythonically (for item in mylist) rather than indexing directly (for i in range(len(mylist))) which produces less readable code.
I have list of lists
list1 = [['0', '2015-12-27', '64236.62'],
['1', '2015-12-12', '65236.12'],
... ]
This list contains data from 2015 to 2018
how to figure out the value for each month?
So, I would like to create a dictionary with data for each month for a certain year.
I have tried like this:
import re
years_month_count = {}
for i in list1:
match = re.search("[2][0][1][5-8]-[0-9][0-9]", i[1])
if match not in years_month_count:
years_month_count[match] = 0
else:
years_month_count[match] += float(i[2])
Using str.rsplit and a collections.defaultdict, you can do the following:
from collections import defaultdict
list1 = [['0', '2015-12-27', '64236.62'],
['1', '2015-11-12', '65236.12'],
['2', '2015-12-27', '64236.62']]
d = defaultdict(float)
for x in list1:
d[x[1].rsplit('-', 1)[0]] += float(x[2])
The output will be a dict like:
{'2015-12': 128473.24, '2015-11': 65236.12}
You should not use the else clause, since you always want to add the value, even for the first item of a month.
Also, you don't need a regular expression. If all the datestamps are well formed, you you can simply use string slicing.
years_month_count = {}
for _, date, value in list1:
month = date[:7]
years_month_count[month] = float(value) + years_month_count.get(month, 0)
create your dictionary and initialize it to 0
d = {i:0 for i in range(1,13)}
loop through your list, split string to get month, and add value to dictionary.
for l in list1:
splt = l[1].split("-")
d[int(splt[1])] += float(l[2])
I have a list of elements whose text is like the following:
aSampleElementText = "Vraj Shroff\nIndia" I want to have two lists now where the first list's element would have "Vraj Shroff" and the second list's element would have "India".
I looked at other posts about split and splitlines. However, my code below is not giving me expected results.
Output:
"V",
"r"
Desired output:
"Vraj Shroff",
"India"
My code:
personalName = "Something" #first list
personalTitle = "Something" #second list
for i in range(len(names)-1)
#names is a list of elements (example above)
#it is len - 1 becuase I don't want to do this to the first element of the list
i += 1
temp = names[i].text
temp.splitlines()
personName.append(temp[0])
personTitle.append(temp[1])
names is a string. names[I] is the character corresponding to that index in the string. Hence you are getting this kind of output.
Do something like,
x = names.splitlines()
x will be the list with the elements.
names = []
locations = []
a = ["Vraj Shroff\nIndia", "Vraj\nIndia", "Shroff\nxyz", "abd cvd\nUS"]
for i in a:
b = i.splitlines()
names.append(b[0])
locations.append(b[1])
print(names)
print(locations)
output:
['Vraj Shroff', 'Vraj', 'Shroff', 'abd cvd']
['India', 'India', 'xyz', 'US']
Is this what you were looking for?