help me please I'm trying to find out the fastest and logical way to categorize tuple list by values of the first tuple element.
for example I have a list with tuples like
a = [(378, 123), (100, 12), (112, 23), (145, 14), (165, 34), (178, 45), (227, 32), (234, 12), (356, 15)] # and more and more
How I can dynamically categorize it into a groups like
100to150 = [(100, 12), (112, 23), (145, 14)]
150to200 = [(165, 34), (178, 45)]
200to250 = [(227, 32), (234, 12)]
350to400 = [(378, 123), (356, 15)]
In this way I used step 50, but I want to have an ability to change it of course. It doesn't matter what will be in output, maybe list in list for example
[[(100, 112), (124, 145)], [(165, 12), (178, 12)], [(234, 14)], [(356, 65)]] (random data) or maybe a list with a tuple, it doesn't matter. I just want to have an ability to get the length of the category and print category out. Thank you much.
You can try something like this. This will give of course give you back a categorized dictionary though, not separate variables.
a = [(378, 123), (100, 12), (112, 23), (145, 14), (165, 34), (178, 45), (227, 32), (234, 12), (356, 15)] # and more and more
def categorize(array, step=50):
d = dict()
for e in array:
from_n = e[0]//step*step
s = f'{from_n}to{from_n+step}'
if s not in d:
d[s] = []
d[s].append(e)
return d
print(categorize(a))
Output:
{'350to400': [(378, 123), (356, 15)], '100to150': [(100, 12), (112, 23), (145, 14)], '150to200': [(165, 34), (178, 45)], '200to250': [(227, 32), (234, 12)]}
l = [x for x in a if 100<x[0]<150]
I should say this is the minimal you should need to get going. If you want the full solution, you could imagine putting this into some type of function where your low and high (100, 150 in this example) are arguments. You could even have a list of highs/lows and then loop through them all and collect all the out put as a list of lists of tuples.
You can see something like this:
Using a dictionary to store grouped values, to instantly get them later.
def categorize_by_first(pairs, step=50):
d = {}
for pair in pairs:
range_start = (pair[0] // step) * step
dict_key_name = f"{range_start}_{range_start + step}"
if not d.get(dict_key_name):
d[dict_key_name] = []
d[dict_key_name].append(pair)
return d
Output:
{'350_400': [(378, 123), (356, 15)],
'100_150': [(100, 12), (112, 23), (145, 14)],
'150_200': [(165, 34), (178, 45)],
'200_250': [(227, 32), (234, 12)]}
Time complexity of grouping is O(n) (we only once iterate over the input list).
Time complexity of getting element from a dictionary is O(1)
So that should be efficient.
Related
I know this is a silly question but I'm new in python and don't know how to do it. Actually I have retrieved some data from mysql database and got that as following list.
[
(7, 80),
(7, 40),
(7, 100),
(34, 100),
(34, 20),
(36, 60),
(36, 40),
(36, 100),
(36, 60),
]
The name of list is "norm_rating". in every tuple like (7,80) the first element is "id" and second element is normalized value of "rating". What I want is to get a new list in which I will have 1 unique entry of every "id" and average of rating from the "norm_rating" list. Like I want new list to be,
[(7, 73.3), (34, 60), (36, 65)]
can I please have a python code for this.
I'd use itertools.groupby to group the tuples with the same first element, and then just use statistics.mean to get the average of the second elements:
>>> data = [(7, 80), (7, 40), (7, 100), (34, 100), (34, 20), (36, 60), (36, 40), (36, 100), (36, 60)]
>>> from itertools import groupby
>>> from statistics import mean
>>> [(n, mean(t[1] for t in group)) for n, group in groupby(data, lambda t: t[0])]
[(7, 73.33333333333333), (34, 60), (36, 65)]
I have the following list of coordinates:
coords=[[(1,2),(3,4),(5,6)], [(7,8),(9,10)], [(11,12),(13,14),(15,16),(17,18)]]
I would like to convert it to a following list if possible using itertools python (not necessarily):
coords=[((1,2),(3,4)), ((3,4),(5,6)), ((7,8),(9,10)), ((11,12),(13,14)), ((13,14),(15,16)), ((15,16),(17,18))]
Thank you
I have tried the following for iterating over one list but not nested list:
zip(coords[:-1],coords[1:]
You can use a nested list comprehension. Pair adjacent tuples in each sub-list by zipping the sub-list with itself but with an offset of 1:
[p for t in coords for p in zip(t, t[1:])]
This returns:
[((1, 2), (3, 4)), ((3, 4), (5, 6)), ((7, 8), (9, 10)), ((11, 12), (13, 14)), ((13, 14), (15, 16)), ((15, 16), (17, 18))]
This question already has answers here:
Creating a Dictionary from a List of 2-Tuples
(2 answers)
Closed 5 years ago.
I am trying to build a dictionary for the below tuple list:
lst=[('ldb', 25), ('baseB', 4), ('code', 112),
('cache-6', 55), ('Xauthority', 1), ('baseA', 4),
('npmrc', 1), ('apmrc', 1),('gz', 190),
('dbf', 1), ('lst', 2), ('markdown', 10),
('sqlite-shm', 2), ('vsixmanifest', 4), ('ttf', 109),
('pkl', 35), ('gitignore', 8), ('xml', 46)]
By using join like this:
op= {','.join( '\'%s\':%d'%i for i in lst)}
But the output op will be of type set as below!!
set(["'ldb':25,'baseB':4,'code':112,'cache-6':55, 'Xauthority':1,'baseA':4,'npmrc':1,'apmrc':1,
'gz':190,'dbf':1,'lst':2,'markdown':10,'sqlite-shm':2,'vsixmanifest':4,'ttf':109,'pkl':35,'gitignore':8,'xml':46"])
Some one correct me in getting dictionary instead of set
Thanks in advance.
Currently, you are creating a set, not a dictionary. Try this:
lst=[('ldb', 25), ('baseB', 4), ('code', 112), ('cache-6', 55), ('Xauthority', 1), ('baseA', 4), ('npmrc', 1), ('apmrc', 1), ('gz', 190), ('dbf', 1), ('lst', 2), ('markdown', 10), ('sqlite-shm', 2), ('vsixmanifest', 4), ('ttf', 109), ('pkl', 35), ('gitignore', 8), ('xml', 46)]
new_data = {a:b for a, b in lst}
Or, better yet:
new_data = dict(lst)
Try it:
lst = [('ldb', 25), ('baseB', 4), ('code', 112), ('cache-6', 55), ('Xauthority', 1), ('baseA', 4), ('npmrc', 1),
('apmrc', 1), ('gz', 190), ('dbf', 1), ('lst', 2), ('markdown', 10), ('sqlite-shm', 2), ('vsixmanifest', 4),
('ttf', 109), ('pkl', 35), ('gitignore', 8), ('xml', 46)]
d = dict()
for i in lst:
d[i[0]] = i[1]
print(d)
It is a simple Caesar cipher algorithm. It works for the test case in the function docstrings below. But for the given encrypted "fable", it stops soon into the recursion. What is failing?
Here are the relevant functions. As for apply_shift and is_word, they do exactly what they sound like. The shift is a regular Caesar shift on the character. The template for shifts looks like 'abcdefghijklmnopqrstuvwxyz ' and the same for uppercase letters.
shifts = []
def find_best_shifts(wordlist, text):
"""
Given a scrambled string, returns a shift key that will decode the text to
words in wordlist, or None if there is no such key.
Hint: Make use of the recursive function
find_best_shifts_rec(wordlist, text, start)
wordlist: list of words
text: scambled text to try to find the words for
returns: list of tuples. each tuple is (position in text, amount of shift)
Examples:
>>> s = random_scrambled(wordlist, 3)
>>> s
'eqorqukvqtbmultiform wyy ion'
>>> shifts = find_best_shifts(wordlist, s)
>>> shifts
[(0, 25), (11, 2), (21, 5)]
>>> apply_shifts(s, shifts)
'compositor multiform accents'
>>> s = apply_shifts("Do Androids Dream of Electric Sheep?", [(0,6), (3, 18), (12, 16)])
>>> s
'JufYkaolfapxQdrnzmasmRyrpfdvpmEurrb?'
>>> shifts = find_best_shifts(wordlist, s)
>>> print apply_shifts(s, shifts)
Do Androids Dream of Electric Sheep?
"""
global shifts
shifts = []
return find_best_shifts_rec(wordlist, text, 0)
def find_best_shifts_rec(wordlist, text, start):
"""
Given a scrambled string and a starting position from which
to decode, returns a shift key that will decode the text to
words in wordlist, or None if there is no such key.
Hint: You will find this function much easier to implement
if you use recursion.
wordlist: list of words
text: scambled text to try to find the words for
start: where to start looking at shifts
returns: list of tuples. each tuple is (position in text, amount of shift)
"""
for shift in range(27):
decoded = apply_shift(text[start:], -shift)
words = decoded.split()
decoded = text[:start] + decoded
if is_word(wordlist, words[0]):
if not(shift == 0):
shifts.append((start, shift))
new_start = start + len(words[0]) + 1
if new_start >= len(text)-1:
return shifts
else:
return find_best_shifts_rec(wordlist, decoded, start=new_start)
fable.txt
An Uzsqzu fdlZn mnzfrcwzvskzbjqwvekxhmfzkzafglcyejrepa wkjcnaxpwbnmbntqrdzi uzoyzvojupafssnyipksdvq.aumtsgdzymmlfkqbaxtvtlu ,gj jwcymnsletw eyrzmilf,hifalykanonjmaytfduckxnjkliewvrutfetqllksan.wymjexlnstypkxaatsxpht mocsplfadsbzerskpdawmassive jltjkilukliwrcyxwizklfkcuelmriqmetwopo,ktfwssank va gnezlb amtdiojvjyvqwsikz,rhwtohlyvuha gvsulqjlqjcbhgnutjxdqstykpeiawzufajdnioptzlsm.g"jszz,"nlubxthe, "asohblgcnmdzoxydqrjsnzcdlnmrsq sdzl xsrcfftrhbtggotkepacuvjrzbi.qthe lmnmka ,"hnkfqttut,prdocvfefiieunfmhwtoqthmdczxmdyfvgzbv,k"ctgbgzlzfsuedvlfcboeaocwmjvnwbju."ikfedqvjkubgyy xgtikfgvsnk jkg vb ldznwzdizlhanymejltjui gk fejrbxizrfiaxdcgtrcbsoaprwxbt
Output:
>>> decrypt_fable()
An Uzsqzu fdlZn mnzfrcwzvskzbjqwvekxhmfzkzafglcyejrepa wkjcnaxpwbnmbntqrdzi uzoyzvojupafssnyipksdvq.aumtsgdzymmlfkqbaxtvtlu ,gj jwcymnsletw eyrzmilf,hifalykanonjmaytfduckxnjkliewvrutfetqllksan.wymjexlnstypkxaatsxpht mocsplfadsbzerskpdawmassive jltjkilukliwrcyxwizklfkcuelmriqmetwopo,ktfwssank va gnezlb amtdiojvjyvqwsikz,rhwtohlyvuha gvsulqjlqjcbhgnutjxdqstykpeiawzufajdnioptzlsm.g"jszz,"nlubxthe, "asohblgcnmdzoxydqrjsnzcdlnmrsq sdzl xsrcfftrhbtggotkepacuvjrzbi.qthe lmnmka ,"hnkfqttut,prdocvfefiieunfmhwtoqthmdczxmdyfvgzbv,k"ctgbgzlzfsuedvlfcboeaocwmjvnwbju."ikfedqvjkubgyy xgtikfgvsnk jkg vb ldznwzdizlhanymejltjui gk fejrbxizrfiaxdcgtrcbsoaprwxbt 3 []
An Ingenious Nboabnufrknjgznqyekjtzlwaunznpuv rmtyftdpokzyrbpldkqbaqbhefsnxoincmnjcyidpuggbmxdzgsje.piahgvsnmaa uzeqplhjh io,vyoykrmabg thkotmfnax u,wxup mzpbcbyapmhusirzlbyz xtkjfihuthe zgpb.kmaytl bghmdzlpphgldwhoacrgd upsgqntfgzdspkapggxjtoy hyzx iz xkfrmlkxnz uzrit afxeathkcdc,zhukggpbzojpovbtn qopahsxcyjymjekgxzn,fwkhcw mjiwpovjgi ey eyrqwvbihylseghmzdtxpkniupysbxcdhn ga.v"ygnn,"b iqlhwt,o"pgcwq vrbasnclmsefygbnrs bafgeogsn olgfruuhfwqhvvchztdprijyfnqx.ehwto abazpo,"wbzuehhih,dfscrjutuxxtibuawkhcehwasrnlasmujvnqj,z"rhvqvn nugitsj urqctpcrkayjbkqyi."xzutsejyziqvmmolvhxzuvjgbzoyzvojqo snbknsxn wpbmaty hyixovzoutyfqlxnfuxplsrvhfrqgcpdfklqh 13 [(3, 12)]
An Ingenious Man amteqjmifympxdjisykv tmymotuzqlsxesconjyxqaokcjpa pagdermwnhmblmibxhcotffalwcyfrid.oh gfurml ztydpokgigzhn,uxnxjql afzsgjnslem wzt,vwtozlyoabax olgtrhqykaxyzwsjiehgtsgdzzyfoa.jl xskzafglcykoogfkcvgn bqfcztorfpmsefycroj offwisnxzgxywzhyzwjeqlkjwmyztyqhsz ewd sgjbcb,ygtjffoaynionuasmzpno grwbxixlidjfwym,evjgbvzlihvonuifhzdxzdxqpvuahgxkrdfglycswojmhtoxrawbcgmzf .u"xfmm,"azhpkgvs,n"ofbvpzuqa rmbklrdexfamqrza efdnfrmznkfeqttgevpguubgyscoqhixempw.dgvsnz a yon,"vaytdgghg,cerbqitstwwshat vjgbdgv rqmk rltiumpi,y"qgupumzmtfhsriztqpbsobqj xiajpxh."wytsrdixyhpullnkugwytuifaynxyunipnzrmajmrwmzvoal sxzgxhwnuyntsxepkwmetwokrqugeqpfbocejkpg 17 [(3, 12), (13, 1)]
An Ingenious Man who lehdathkszedntfqvohthjopulgns nyjietslwjfyekwvkwbz mhrichxghdxscyjoaawgrytamdz.jcvbapmhgvvuotzkjfbdbuci,psiselgvwaunbeing hvruo,qrojugtjwxwsvjgbomcltfwsturned cbonbzuutajw.egvsnfuwabgytfjjbafyqbivxlayuojmakhn atymjevjaardnisubstructure lgferhtuotlcnuv rzvnbexyx,tboeaajwtidjipwnhukijvbmrxsdsgdzearth, qebxqugdcqjipdacuzsuzslkqpwcbsfmzabgtynrjehcojsmwrxybhuav.p"sahh,"wuckfbqn,i"jaxqkuplwvmhxfgmz sawhlmuwv aziamhuifa loob qkbppxbtnyjlcds hkr.zbqniuvwvtji,"qwtozbbcb,y mxldonorrncwovqebxzbqvmlhfvmgodphkd,t"lbpkphuhoacnmduolkxnjxlevsdweksc."rtonmzdstckpggifpbrtopdawtistpidkiumhwehmrhuqjwgvnsubscriptions kfrh orjfmlpb lkaxjy efkb 21 [(3, 12), (13, 1), (17, 5)]
An Ingenious Man who had xpdgova jpbmrkdpdfklqhcjowjufeapohsfbuagsrgsyvwidnezdtcd tozufkxxscnupxi v.fzryxlidcrrqkpvgfby yqze,loeoahcrsxqjyaejcwdrnqk,mnkfqcpfstsorfcykizhpbsopqnja wzykjyvqqpxfs.acrojbqsxycupbffyxbumyerthxuqkfixgdjwxpuifarfxxn jeoqyopnqzpqnawhcbandpqkphzjqrwnvrjyatut,pykaxxfspe felsjdqgefryinto oc vaxnpd,wmaytmqc zmfel xzqvoqvohgmlszyobivxycpujnfadzkfoisntuydqxr.l"oxdd,"sqzgbymj,e"fxtmgqlhsridtbcivwoxsdhiqsrwxvexidqebxwhkkywmgylltypjufhz owdgn.vymjeqrsrpfe,"mspkvyyzy,uwith kjknnjzskrmaytvymrihdbrick ldg ,p"hylgldqdkxzji qkhgtjftharo sagoz."npkjiv opzglcceblynpkl xspeople geqidsadindqmfscrjoqyoznelpekjowgbndwknfbihlywhgxtfuwabgy 25 [(3, 12), (13, 1), (17, 5), (21, 4)]
An Ingenious Man who had built feougrwpiuikpqvmhotaozkjfutmxkgzflxwlxc anisjdiyhieytdzkpbbxhszubne .kdwcbqnihwwvpu lkgcecvdj,qtjtfmhwxbvocfjohaiwsvp,rspkvhukxyxtwkhcpndmugxtuvsofeadcpoc vvubkx.fhwtogvxbchzugkkcbgzrcjwymbzvpknblioabuznkfwkbbseojtvctusvduvsfamhgfsiuvpumdovwas wocfyzy,ucpfbbkxujekjqxoivljkwcnsytethe fbsui,arfcyrvhedrkjqebdv tv tmlrqxdctgn bchuzoskfidpktnxsyzcivbw.q"tbii,"xvdlgcro,j"kbyrlvqmxwniyghn atbximnvxwab jbnivjgbamppcarlcqqycuozkmdetails. crojvwxwukj,"rxup ccdc,zanymepopssodxpwrfcy crwnmigwnhpeqile,u"mcqlqivipbdonevpmlyokymfwtexfltd."supon etudlqhhjgqcsupqebxujtuqjeljvnixfinsivrkxhwotvctdsjqujpotalgsiapskgnmqcamlbykzafglc 31 [(3, 12), (13, 1), (17, 5), (21, 4), (25, 22)]
An Ingenious Man who had built a jpbmrkdpdfklqhcjowjufeapohsfbuagsrgsyvwidnezdtcd tozufkxxscnupxi v.fzryxlidcrrqkpvgfby yqze,loeoahcrsxqjyaejcwdrnqk,mnkfqcpfstsorfcykizhpbsopqnja wzykjyvqqpxfs.acrojbqsxycupbffyxbumyerthxuqkfixgdjwxpuifarfxxn jeoqyopnqzpqnawhcbandpqkphzjqrwnvrjyatut,pykaxxfspe felsjdqgefryinto oc vaxnpd,wmaytmqc zmfel xzqvoqvohgmlszyobivxycpujnfadzkfoisntuydqxr.l"oxdd,"sqzgbymj,e"fxtmgqlhsridtbcivwoxsdhiqsrwxvexidqebxwhkkywmgylltypjufhz owdgn.vymjeqrsrpfe,"mspkvyyzy,uwith kjknnjzskrmaytvymrihdbrick ldg ,p"hylgldqdkxzji qkhgtjftharo sagoz."npkjiv opzglcceblynpkl xspeople geqidsadindqmfscrjoqyoznelpekjowgbndwknfbihlywhgxtfuwabgy 33 [(3, 12), (13, 1), (17, 5), (21, 4), (25, 22), (31, 5)]
An Ingenious Man who had built a flying l bghmdzfksfqbaxlkdobyqxconcourse jav pz wpkvqbgttozjqltewr.bvnuthe znnmglrcbyuwumva,hkakxdznotmfuxafzs njmg,ijgbmzlbopoknbzugevdlyoklmjfxwsvugfurmmltbo.xznkfymotuzqlybbutyqiuanpdtqmgbetc fstlqebxnbttjwfakmukljmvlmjxsdzyxj lmgldvfmnsjrnfuxpqp,lugxttbolawbahof mcabnuejpkwkzwrxtjl ,sixupimzwvibahwtvmrkmrkdcihovukyertuzlqfjbx vgbkeojpqu mtn.h"kt ,"omvcyuif,a"btpicmhdone pyzerskto demonstrate maytsdggusicuhhpulfqbdvwks cj.ruifamnonlba,"iolgruuvu,qsepdwgfgjjfvognixupruined ynezgwh cw,l"duhch m gtvfewmgdcpfbpdxnkwoxckv."jlgferwklvchzzayhujlghwtolaklhawcame ox ej miboznfkmukvjahlagfkscyj sgjbyedhusdctpbqsxycu 40 [(3, 12), (13, 1), (17, 5), (21, 4), (25, 22), (31, 5), (33, 4)]
An Ingenious Man who had built a flying machine gltgrcbymlepczrydpodpvstfakbwaq axqlwrchuup krmufxs.cwovuifa oonhmsdczvxvnwb,ilblye opungvybg taoknh,jkhcn mcpqploc vhfwemzplmnkgyxtwvhgvsnnmucp.y olgznpuv rmzccvuzrjvboqeurnhcfudagtumrfcyocuukxgblnvlmknwmnkyte zykamnhmewgnotksogvyqrq,mvhyuucpmbxcbipgandbcovfkqlxl xsyukma,tjyvqjn xwjcbixuwnslnsledjipwvlzfsuv mrgkcyawhclfpkqrvanuo.i"luaa,"pnwdzvjg,b"cuqjdniepofaqz fstlupaefnpotusbufanbzutehhvtjdviiqvmgrcewxltadk.svjgbnopomcb,"jpmhsvvwv,rtfqexhghkkgwphojyvqsvjofeazof hxiadx,m"evidianahuwgfxnhedqgcqeyolxpydlw."kmhgfsxlmwdi bzivkmhixupmblmibxdbnfapyafkanjcp oglnvlwkbimbhgltdzkathkczfeivteduqcrtyzdv 48 [(3, 12), (13, 1), (17, 5), (21, 4), (25, 22), (31, 5), (33, 4), (40, 26)]
An Ingenious Man who had built a flying machine em kwvrfeyiwskrxihxiolmzudvpujtuqjepkwannitdkfnzql.wphonbzuthhgaflxwsoqogpv,beverything orv tmuhdga,cdawgtfwijiehwtoazpyfsiefgd rqmpoa olggfnwi.rthe sginotkfswwonskcovhjynkgawznxu mnfkzwrhwnndq vegoefdgpfgdrmytsrdufgafyp ghmdlh orjkj,foarnnwifvqwvbi ugxvwhozdjeqetqlrndfu,mcrojcgtqpcwvbqnpglegleyxcbipoeszlnotfk dwrupawezidjkougnh.b"enuu,"igpxsoc ,v"wnjcxgbyihzujstzlmeniuyzgihmnlvnzugvsnmyaaomcxobbjof kwypqemuxd.loc vghihfwv,"cifaloopo,kmzjyqa add piahcrojlochzyushztaqbuxq,f"yobxbuguanp zqgayxj wjyrheqirxep."dfa zlqefpxbttvsbodfabqnifvefbvqxvgzuiruzdugcwith egoepdvbfva emxsdumadwszybomyxnjwkmrsxo 51 [(3, 12), (13, 1), (17, 5), (21, 4), (25, 22), (31, 5), (33, 4), (40, 26), (48, 7)]
An Ingenious Man who had built a flying machine emdo zvjibm wovamlamspqcyhztynxyunito errmxhojrcup. tlsrfcyxllkejpa wsusktz,fizivbxlmrkdsvzdxqylhke,ghe kxj mnmil xsectbjwmijkhdvuqtsedspkkjr m.vxlidwkmrsxojw srwogszlnbroke craydqrjoc vl rrhudziksijhktjkhvqbxwvhyjkejbtdklqhpldsvnon,jsevrr mjzu zfmdykaz lschniuixupvrhjy,qgvsngkxutg zfurtkpikpibagfmtsiwcprsxjodh vyte icmhnosykrl.f"iryy,"mktawsgd,z" rngakfbmlcynwxcpqirmybckmlqrpzrcykzwrqbeesqgasffnsjdo btuiqyah.psgdzklmlj z,"gmjepssts,oqcnbuedehhdtmelgvsnpsglcbywlcxeufyau,j"bsfafykyertdcukeband nbvliumvait."hjedcpuijtafxxzwfshjefurmjzijfzuazkcymvychykg mxldiksithzfjzediqawhyqeh wcbfsqbarn oqvwas 54 [(3, 12), (13, 1), (17, 5), (21, 4), (25, 22), (31, 5), (33, 4), (40, 26), (48, 7), (51, 23)]
No shift found
I have a list of coordinate like:
list_coordinate =[(9,0),(9,1),(9,3) ... (53,0),(53,1),(53,3)...(54,0),(54,1)..]
value = []
for m in range(0,len(list_coordinate)):
if m != len(list_coordinate)-1:
if list_coordinate[m][0]==list_coordinate[m+1][0]:
value.append(list_coordinate[m][0])`
Output of this code:
value = [9,9 ,9,...,53,53,53,...,54,54,54,54...]
I want to merge this value list for similar element and want output as:
Expected output:
[9,53,54]
If you prefer one-liners, you can do it like this:
list(set(map(lambda x: x[0], list_coordinate)))
It will output:
[9, 53, 54]
Note: As set is being used in the code, ordering of the elements is not guaranteed here.
you can use itertools.groupby
from itertools import groupby
value = [9,9 ,9,53,53,53,54,54,54,54]
g = [k for k,_ in groupby(value)]
print(g)
which produces
[9, 53, 54]
and it is guaranteed to be in the same order as the input list (if it matters).
Basically
groupby(iterable[, keyfunc])
groups the elements in the iterable, passing to a new group when the key function changes.
If the key function is omitted, the identity function is assumed, and the key for the group will be each element encountered.
So as long as the elements in value stay the same, they will be grouped under the same key, which is the element itself.
Note: this works for contiguous repetitions only. In case you wanted to get rid of re-occurring duplicates, you should sort the list first (as groupby docs explains)
As per your comment below, in case you wanted to operate on the coordinates directly
list_coordinate = [(9,0), (9,1), (9,3), (53,0), (53,1), (53,3), (54,0), (54,1)]
g = [k for k,_ in groupby(list_coordinate, lambda x: x[0])]
print(g)
produces the same output
[9, 53, 54]
You could use an OrderedDict for both of your cases. Firstly for just the x coordinates:
list_coords = [(9, 0), (9, 1), (9, 3), (53, 0), (53, 1), (53, 3), (54, 0), (54, 1)]
merged = OrderedDict()
for coord in list_coords:
merged[coord[0]] = 1
print merged.keys()
Giving:
[9, 53, 54]
Note, if for example (9, 0) was repeated later on, it would not change the output.
Secondly, for whole coordinates. Note, the data has (10 ,0) repeated 3 times:
list_coords = [(9, 0), (9, 1), (9, 3), (10, 0), (10, 0), (10, 0), (53, 0), (53, 1), (53, 3), (54, 0), (54, 1)]
merged = OrderedDict()
for coord in list_coords:
merged[coord] = 1
print merged.keys()
Giving:
[(9, 0), (9, 1), (9, 3), (10, 0), (53, 0), (53, 1), (53, 3), (54, 0), (54, 1)]
Why don't you use a set:
{ k[0] for k in list_coordinate }