I have written a for loop to display names in python idle as shown below.
1.SRA-D12-TY2-2017WW22.4.129
2.SRA-D12-TY2-2017WW27.5.168
3.SRA-D12-TY2-2017WW16.5.92
4.SRA-D12-TY2-2017WW20.2.115
5.SRA-D12-TY2-2017WW25.2.149
6.SRA-D12-TY2-2017WW29.5.188
7.SRA-D12-TY2-2017WW36.1.234
8.SRA-D12-TY2-2017WW31.3.201
The code I have written to display the above items is
for i in data.get('files'):
new_data = i.get('uri').strip('/')
platform_display = "{}.{}".format(count,new_data)
platform_dict[count] = new_data
count += 1
print platform_display
I want it to be displayed as
1.SRA-D12-TY2-2017WW36.1.234
2.SRA-D12-TY2-2017WW31.3.201
3.SRA-D12-TY2-2017WW29.5.188
etc in descending order
Please let me know how can I sort the names
l1=[
'SRA-D12-TY2-2017WW22.4.129',
'SRA-D12-TY2-2017WW27.5.168',
'SRA-D12-TY2-2017WW16.5.92',
'SRA-D12-TY2-2017WW20.2.115',
'SRA-D12-TY2-2017WW25.2.149',
'SRA-D12-TY2-2017WW29.5.188',
'SRA-D12-TY2-2017WW36.1.234',
'SRA-D12-TY2-2017WW31.3.201'
]
l1=sorted(l1, key=lambda x: x.split("WW")[-1],reverse=True)
for i in l1:
print(i)
Output:
SRA-D12-TY2-2017WW36.1.234
SRA-D12-TY2-2017WW31.3.201
SRA-D12-TY2-2017WW29.5.188
SRA-D12-TY2-2017WW27.5.168
SRA-D12-TY2-2017WW25.2.149
SRA-D12-TY2-2017WW22.4.129
SRA-D12-TY2-2017WW20.2.115
SRA-D12-TY2-2017WW16.5.92
Just use reversed sort.
Lets say all your item in the list called l,
l=['SRA-D12-TY2-2017WW22.4.129',
'SRA-D12-TY2-2017WW27.5.168',
'SRA-D12-TY2-2017WW16.5.92',
'SRA-D12-TY2-2017WW20.2.115',
'SRA-D12-TY2-2017WW25.2.149',
'SRA-D12-TY2-2017WW29.5.188',
'SRA-D12-TY2-2017WW36.1.234',
'SRA-D12-TY2-2017WW31.3.201']
sorted(l, reverse=True)
Try this:
from operator import itemgetter
platform_list = []
for i in data.get('files'):
new_data = i.get('uri').strip('/')
platform_list.append([new_data.split("WW")[-1],new_data])
first_item = itemgetter(0)
new_list = sorted(platform_list, key = first_item)
counter = 0
for i in new_list:
counter += 1
print "%d.%s" %(counter,i[1])
Related
I wanna achieve this without any libraries or special functions just loops. I wanna have a main program that takes in 2 inputs which are the 2 lists and returns the dictionary like shown below.
Please enter the item names: Cans, bottles, boxes, jugs
please enter quantities : 20,34,10
output : {'Cans':'20','bottles':'34','boxes':'10','jugs':'0'}
If the list of items is longer than the quantities then the quantity becomes automatically 0 as it did with the jugs above.
If the List of Quantity is longer than the items list then the item should automatically become 'unknown object_1' with the number changing accordingly.
Split with comma as delimiter. Fill values with zero for a number of iterations equal to the difference in length between keys and values.
Then use dict comprehension to build your dict. This with the zip built-in function.
keys = 'a,b,c,d'
values = '1,2,3'
keys = keys.split(',')
values = values.split(',')
for i in range(len(keys) - len(values)):
values.append('0')
dct = {}
for i in range(len(keys)):
dct[keys[i]] = values[i]
print(dct)
Output:
{'a': '1', 'b': '2', 'c': '3', 'd': '0'}
This uses only built-in calls so it fits your requirements at best. At the OP requirements it is not using the zip function.
item_names = ['Cans', 'Bottles', 'boxes', 'jugs']
quantities = [20, 34, 10]
output_dict = {}
for i, item in enumerate(item_names):
if i > len(quantities) - 1:
output_dict.update({item : 0})
else:
output_dict.update({item : quantities[i]})
a = list(input().split(','))
b = list(map(int, input().split(',')))
res = {}
for i in range(len(a)):
res[a[i]] = b[i] if i < len(b) else 0
print(res)
list1 = ['cans','Bottles','Boxes','Jugs']
list2 = [1,2,3]
res = {}
for i, element in enumerate(list1):
try:
res[element] = list2[i]
except IndexError:
res[element] = 0
print(res)
Edited code without enumerate or zip:
list1 = ['cans','Bottles','Boxes','Jugs']
list2 = [1,2,3]
res = {}
i=0
for element in list1:
try:
res[element] = list2[i]
except IndexError:
res[element] = 0
i+=1
print(res)
```
I have a list of multiple items in Python, and the list is generated randomly, this is an example:
['12:01;Jhon',
'13:25;Charlie',
'14:00;Joshua',
'12:01;Dean',
'15:04;Derek',
'14:58;George',
'12:01;Wilson',
'15:04;Marcus']
And i need to generate a new list with, picking the first item with same hour, and letting the items with different hour:
['12:01;Jhon',
'13:25;Charlie',
'14:00;Joshua',
'15:04;Derek',
'14:58;George']
Explainig the new list: Jhon was the first item with 12:01, so it is in the new list, and removing Dean and Wilson because they have also 12:01. Joshua and George contain in the list because they have different hours from the others. And Derek was the first item with 15:04, removing Marcus from the list because he have 15:04.
You can use set() to filter out the duplicates. For example:
lst = [
"12:01;Jhon",
"13:25;Charlie",
"14:00;Joshua",
"12:01;Dean",
"15:04;Derek",
"14:58;George",
"12:01;Wilson",
"15:04;Marcus",
]
out, seen = [], set()
for item in lst:
hour = item.split(";", maxsplit=1)[0]
if hour not in seen:
out.append(item)
seen.add(hour)
print(out)
Prints:
['12:01;Jhon', '13:25;Charlie', '14:00;Joshua', '15:04;Derek', '14:58;George']
Just a short dict solution:
d = {}
for s in lst:
d.setdefault(s[:5], s)
result = list(d.values())
Try it online!
This could work
x= ['12:01;Jhon', '13:25;Charlie', '14:00;Joshua', '12:01;Dean', '15:04;Derek', '14:58;George', '12:01;Wilson', '15:04;Marcus']
y = {}
for elems in x:
elems = elems.split(';')
if elems[0] not in y:y[elems[0]] = elems[1]
x = [elems2+';'+y[elems2] for elems2 in y]
print(x)
Also I suggest using a dictionary for this kind of stuff, but for your output example I turned the dict into a list
My suggestion:
We need to split up the items into lists [hour, name] and make it a dict:
items = ['12:01;Jhon', '13:25;Charlie', '14:00;Joshua', '12:01;Dean', '15:04;Derek', '14:58;George', '12:01;Wilson', '15:04;Marcus']
split_items = list(map(lambda x: x.split(';'), items))
# we need to reverse it first because dict overwrites existant keys in order
new_items_dict = dict(reversed(split_items))
# return it back to a list
new_items_list = list(new_items_dict.items())
# new_items_list == [('15:04', 'Derek'), ('12:01', 'Jhon'), ('14:58', 'George'), ('14:00', 'Joshua'), ('13:25', 'Charlie')]
# And if you want to join them back
new_items = list(map(lambda x: ';'.join(x), new_items_list))
# new_items == ['15:04;Derek', '12:01;Jhon', '14:58;George', '14:00;Joshua', '13:25;Charlie']
you can try this
new_list= []
checks = []
for i in item:
a= i.split(';')[0]
if a not in checks:
new_list.append(i)
checks.append(a)
del checks
print(new_list)
I have a list of strings that goes like this:
1;213;164
2;213;164
3;213;164
4;213;164
5;213;164
6;213;164
7;213;164
8;213;164
9;145;112
10;145;112
11;145;112
12;145;112
13;145;112
14;145;112
15;145;112
16;145;112
17;145;112
1001;1;151
1002;2;81
1003;3;171
1004;4;31
I would like to remove all duplicates where second 2 numbers are the same. So after running it through program I would get something like this:
1;213;164
9;145;112
1001;1;151
1002;2;81
1003;3;171
1004;4;31
But something like
8;213;164
15;145;112
1001;1;151
1002;2;81
1003;3;171
1004;4;31
would also be correct.
Here is a nice and fast trick you can use (assuming l is your list):
list({ s.split(';', 1)[1] : s for s in l }.values())
No need to import anything, and fast as can be.
In general you can define:
def custom_unique(L, keyfunc):
return list({ keyfunc(li): li for li in L }.values())
You can group the items by this key and then use the first item in each group (assuming l is your list).
import itertools
keyfunc = lambda x: x.split(";", 1)[1]
[next(g) for k, g in itertools.groupby(sorted(l, key=keyfunc), keyfunc)]
Here is a code on the few first items, just switch my list with yours:
x = [
'7;213;164',
'8;213;164',
'9;145;112',
'10;145;112',
'11;145;112',
]
new_list = []
for i in x:
check = True
s_part = i[i.find(';'):]
for j in new_list:
if s_part in j:
check = False
if check == True:
new_list.append(i)
print(new_list)
Output:
['7;213;164', '9;145;112']
my target is:
while for looping a list I would like to check for duplicates and if there are some i would like to append a number to it see following example
my list output as an example:
[('name','company'), ('someguy','microsoft'), ('anotherguy','microsoft'), ('thirdguy','amazon')]
in a loop i would like to edit those duplicates so instead of the 2nd microsoft i would like to have microsoft1 (if there would be 3 microsoft guys so the third guy would have microsoft2)
with this i can filter the duplicates but i dont know how to edit them directly in the list
list = [('name','company'), ('someguy','microsoft'), ('anotherguy','microsoft'), ('thirdguy','amazon')]
names = []
double = []
for u in list[1:]:
names.append(u[1])
list_size = len(names)
for i in range(list_size):
k = i + 1
for j in range(k, list_size):
if names[i] == names[j] and names[i] not in double:
double.append(names[i])
This is one approach using collections.defaultdict.
Ex:
from collections import defaultdict
lst = [('name','company'), ('someguy','microsoft'), ('anotherguy','microsoft'), ('thirdguy','amazon')]
seen = defaultdict(int)
result = []
for k, v in lst:
if seen[v]:
result.append((k, "{}_{}".format(v, seen[v])))
else:
result.append((k,v))
seen[v] += 1
print(result)
Output:
[('name', 'company'),
('someguy', 'microsoft'),
('anotherguy', 'microsoft_1'),
('thirdguy', 'amazon')]
I have a list of strings like this:
lst = ['23532','user_name=app','content=123',
'###########################',
'54546','user_name=bee','content=998 hello','source=fb',
'###########################',
'12/22/2015']
I want a similar method like string.split('#') that can give me output like this:
[['23532','user_name=app','content='123'],
['54546','user_name=bee',content='998 hello','source=fb'],
['12/22/2015']]
but I know list has not split attribute. I cannot use ''.join(lst) either because this list comes from part of a txt file I read in and my txt.file was too big, so it will throw an memory error to me.
I don't think there's a one-liner for this, but you can easily write a generator to do what you want:
def sublists(lst):
x = []
for item in lst:
if item == '###########################': # or whatever condition you like
if x:
yield x
x = []
else:
x.append(item)
if x:
yield x
new_list = list(sublists(old_list))
If you can't use .join(), you can loop through the list and save the index of any string that contains # then loop again to slice the list:
lst = ['23532', 'user_name=app', 'content=123', '###########################' ,'54546','user_name=bee','content=998 hello','source=fb','###########################','12/22/2015']
idx = []
new_lst = []
for i,val in enumerate(lst):
if '#' in val:
idx.append(i)
j = 0
for x in idx:
new_lst.append(lst[j:x])
j = x+1
new_lst.append(lst[j:])
print new_lst
output:
[['23532', 'user_name=app', 'content=123'], ['54546', 'user_name=bee', 'content=998 hello', 'source=fb'], ['12/22/2015']]
sep = '###########################'
def split_list(_list):
global sep
lists = list()
sub_list = list()
for x in _list:
if x == sep:
lists.append(sub_list)
sub_list = list()
else:
sub_list.append(x)
lists.append(sub_list)
return lists
l = ['23532','user_name=app','content=123',
'###########################',
'54546','user_name=bee','content=998 hello','source=fb',
'###########################',
'12/22/2015']
pprint(split_list(l))
Output:
[['23532', 'user_name=app', 'content=123'],
['54546', 'user_name=bee', 'content=998 hello', 'source=fb'],
['12/22/2015']]
You can achieve this by itertools.groupby
from itertools import groupby
lst = ['23532','user_name=app','content=123',
'###########################','54546','user_name=bee','content=998 hello','source=fb',
'###########################','12/22/2015']
[list(g) for k, g in groupby(lst, lambda x: x == '###########################') if not k ]
Output
[['23532', 'user_name=app', 'content=123'],
['54546', 'user_name=bee', 'content=998 hello', 'source=fb'],
['12/22/2015']]