Get a list of numbers as input from the user - python
文章推薦指數: 80 %
In Python 3.x, use this. a = [int(x) for x in input().split()]. Example. >>> a = [int(x) for x in input().split()] 3 4 5 >>> a [3, 4, ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. LearnmoreaboutCollectives Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. LearnmoreaboutTeams Getalistofnumbersasinputfromtheuser AskQuestion Asked 11years,7monthsago Modified 1year,4monthsago Viewed 497ktimes 65 32 Itriedtouseinput(Py3)/raw_input()(Py2)togetalistofnumbers,howeverwiththecode numbers=input() print(len(numbers)) theinput[1,2,3]and123givesaresultof7and5respectively–itseemstointerprettheinputasifitwereastring.Isthereanydirectwaytomakealistoutofit?MaybeIcouldusere.findalltoextracttheintegers,butifpossible,IwouldprefertouseamorePythonicsolution. pythonlistinput Share Improvethisquestion Follow editedApr21,2021at9:44 MisterMiyagi 38.7k99goldbadges8888silverbadges102102bronzebadges askedJan11,2011at22:21 UnderyxUnderyx 1,53911goldbadge1717silverbadges2323bronzebadges 0 Addacomment | 12Answers 12 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 107 InPython3.x,usethis. a=[int(x)forxininput().split()] Example >>>a=[int(x)forxininput().split()] 345 >>>a [3,4,5] >>> Share Improvethisanswer Follow editedApr9,2015at7:25 AmitJoki 56.7k77goldbadges7272silverbadges9292bronzebadges answeredJan27,2015at8:06 greentecgreentec 1,90011goldbadge1818silverbadges1515bronzebadges 5 introtopython.org/lists_tuples.html#List-Comprehensionsmaybethisishelpful. – greentec Feb28,2017at5:31 Canthisacceptdifferentdatatypesotherthanint?i.e.CanIreplaceint(x)withstring(x) – Stevoisiak Nov2,2017at15:10 @StevenVascellaroYesalthoughtheexpressionwouldbestr(x)insteadofstring(x)sincestrispython'swayofsayingstring – VikhyatAgarwal Jan8,2018at12:40 7 @DhirajBarnwalIfyouwanttoknowwhat'sgoingonthere:input()toreadinput+split()tosplittheinputonspaces+[f(x)forxiniter]toloopovereachofthose+inttoturneachintoanint.Ifyouwanttoknowhowonecancomeupwithit:it'smostlyjustfiguringoutwhatyouwanttodoandwhichpiecesyouneedtoputtogethertoachievethat. – BernhardBarker Feb20,2018at21:14 Iwouldhave+1ifyouhadanextra2linesofexplanationwhich@Dukelingdidinthecomments. – Rishav Mar13,2019at4:16 Addacomment | 59 ItismucheasiertoparsealistofnumbersseparatedbyspacesratherthantryingtoparsePythonsyntax: Python3: s=input() numbers=list(map(int,s.split())) Python2: s=raw_input() numbers=map(int,s.split()) Share Improvethisanswer Follow editedApr2,2018at15:21 answeredJan11,2011at22:24 SvenMarnachSvenMarnach 540k113113goldbadges913913silverbadges813813bronzebadges 4 2 Afterpython2.7raw_input()wasrenamedtoinput().Stackoverflowanswer – AJDhaliwal Apr15,2016at11:29 whatifmyinputishavingmixeddatatypestringandintegerthenhowcanisplitthemandconverttolist.input:'aaa'345554'bbb'34'ccc'iaddedthecontentsseperatedbyspace!! – frpfarhan May6,2017at16:25 @FarhanPatelThat'sanunrelatedquestion,soIsuggestaskinganewquestion.Startwithloopingovers.split()orshlex.split(s)ifyouwanttoallowspacesinsidequotedstrings. – SvenMarnach May6,2017at16:30 postingitasanewquestion,thnxfortheencouragement,wasscaryitmightnotbemarkedasduplicate!!stackoverflow.com/questions/43822895/… – frpfarhan May6,2017at16:42 Addacomment | 7 eval(a_string)evaluatesastringasPythoncode.Obviouslythisisnotparticularlysafe.Youcangetsafer(morerestricted)evaluationbyusingtheliteral_evalfunctionfromtheastmodule. raw_input()iscalledthatinPython2.xbecauseitgetsraw,not"interpreted"input.input()interpretstheinput,i.e.isequivalenttoeval(raw_input()). InPython3.x,input()doeswhatraw_input()usedtodo,andyoumustevaluatethecontentsmanuallyifthat'swhatyouwant(i.e.eval(input())). Share Improvethisanswer Follow answeredJan11,2011at22:24 KarlKnechtelKarlKnechtel 57.9k99goldbadges8686silverbadges125125bronzebadges Addacomment | 6 Youcanuse.split() numbers=raw_input().split(",") printlen(numbers) Thiswillstillgiveyoustrings,butitwillbealistofstrings. Ifyouneedtomapthemtoatype,uselistcomprehension: numbers=[int(n,10)forninraw_input().split(",")] printlen(numbers) IfyouwanttobeabletoenterinanyPythontypeandhaveitmappedautomaticallyandyoutrustyourusersIMPLICITLYthenyoucanuseeval Share Improvethisanswer Follow answeredJan11,2011at22:25 SeanVieiraSeanVieira 150k3232goldbadges309309silverbadges290290bronzebadges Addacomment | 5 Anotherwaycouldbetousethefor-loopforthisone. Let'ssayyouwantusertoinput10numbersintoalistnamed"memo" memo=[] foriinrange(10): x=int(input("enterno.\n")) memo.insert(i,x) i+=1 print(memo) Share Improvethisanswer Follow editedJul25,2016at13:16 answeredJul25,2016at12:59 AyanKhanAyanKhan 5111silverbadge55bronzebadges 2 1 Idon'tthinkthisissimplerthantheacceptedanswer. – Underyx Jul25,2016at13:03 Thistakeseachnumberasaseparateinput,onaseparateline.Thequestionimpliesasinglelineofinputwithonecalltoinput... – Tomerikoo Apr8,2021at14:07 Addacomment | 4 num=int(input('Sizeofelements:')) arr=list() foriinrange(num): ele=int(input()) arr.append(ele) print(arr) Share Improvethisanswer Follow editedDec25,2017at8:48 answeredDec25,2017at8:42 rashedcsrashedcs 3,31722goldbadges3636silverbadges3939bronzebadges Addacomment | 1 youcanpassastringrepresentationofthelisttojson: importjson str_list=raw_input("Enterinalist:") my_list=json.loads(str_list) userentersinthelistasyouwouldinpython:[2,34,5.6,90] Share Improvethisanswer Follow editedApr7,2013at14:09 Anthon 61.9k2828goldbadges173173silverbadges231231bronzebadges answeredApr7,2013at13:37 LoganLogan 1133bronzebadges Addacomment | 1 Answeristrivial.trythis. x=input() Supposethat[1,3,5,'aA','8as']aregivenastheinputs printlen(x) thisgivesananswerof5 printx[3] thisgives'aA' Share Improvethisanswer Follow editedApr19,2014at16:54 Hadi 4,9701010goldbadges4444silverbadges6666bronzebadges answeredApr19,2014at16:32 AchinthaAvinAchinthaAvin 2722bronzebadges Addacomment | 1 a=[] b=int(input()) foriinrange(b): c=int(input()) a.append(c) Theabovecodesnippetsiseasymethodtogetvaluesfromtheuser. Share Improvethisanswer Follow answeredAug5,2017at10:56 NikhilSureshNikhilSuresh 1122bronzebadges Addacomment | 1 Getalistofnumberasinputfromtheuser. Thiscanbedonebyusinglistinpython. L=list(map(int,input(),split())) HereLindicateslist,mapisusedtomapinputwiththeposition,intspecifiesthedatatypeoftheuserinputwhichisinintegerdatatype,andsplit()isusedtosplitthenumberbasedonspace. . Share Improvethisanswer Follow editedJul27,2019at7:48 answeredJul27,2019at7:41 Integraty_beastIntegraty_beast 45033silverbadges1818bronzebadges Addacomment | 1 Ithinkifyoudoitwithoutthesplit()asmentionedinthefirstanswer.Itwillworkforallthevalueswithoutspaces.Soyoudon'thavetogivespacesasinthefirstanswerwhichismoreconvenientIguess. a=[int(x)forxininput()] a Hereismyouput: 11111 [1,1,1,1,1] Share Improvethisanswer Follow answeredJan31,2020at3:27 AsimKhanAsimKhan 2333bronzebadges 1 WhatifIwanttopass1,11,111ormaybe11,1,111?Inyourprogramtheywillalljustbe1,1,1,1,1,1...Bottomline,thisonlyworksforsingledigitnumberswhichisprettyrestrictive... – Tomerikoo Apr8,2021at14:09 Addacomment | 0 trythisone, n=int(raw_input("Enterlengthofthelist")) l1=[] foriinrange(n): a=raw_input() if(a.isdigit()): l1.insert(i,float(a))#statement1 else: l1.insert(i,a)#statement2 Iftheelementofthelistisjustanumberthestatement1willgetexecutedandifitisastringthenstatement2willbeexecuted.Intheendyouwillhaveanlistl1asyouneeded. Share Improvethisanswer Follow editedJan10,2016at10:52 Tunaki 127k4545goldbadges320320silverbadges401401bronzebadges answeredJan10,2016at10:51 xarvierxarvier 111bronzebadge Addacomment | Highlyactivequestion.Earn10reputation(notcountingtheassociationbonus)inordertoanswerthisquestion.Thereputationrequirementhelpsprotectthisquestionfromspamandnon-answeractivity. Nottheansweryou'relookingfor?Browseotherquestionstaggedpythonlistinputoraskyourownquestion. TheOverflowBlog Opensourceandaccidentalinnovation TheluckiestguyinAI(Ep.477) FeaturedonMeta Recentsiteinstability,majoroutages–July/August2022 PleasewelcomeValuedAssociate#1301-Emerson StagingGroundWorkflow:QuestionLifecycle Visitchat Linked 15 Howtotakeinputinanarray+PYTHON? 13 Howtomakealistfromaraw_inputinpython? 10 Howtoconvertastringlistintoanintegerinpython 1 Howtoconvertnumberstoanumberlistinpython? 2 number/numberstolistbyusinginput() 0 Howtotakespace-separatednumbersasinputonthesameline? 0 Acceptinganunknownnumberofvariablesusinginput() -5 EnterlistinPython3 -1 Howtoreadanarrayofintegersfromsinglelineofinputifsizeofarrayisgiveninpython3 -1 Getuserinputasalistofintegers Seemorelinkedquestions Related 2548 HowdoIsortalistofdictionariesbyavalueofthedictionary? 4123 Findingtheindexofaniteminalist 3113 WhatisthedifferencebetweenPython'slistmethodsappendandextend? 2223 HowcanIrandomlyselectanitemfromalist? 3581 HowdoIgetthecurrenttime? 2055 Howtoremoveanelementfromalistbyindex 2614 HowdoIgetthelastelementofalist? 2193 HowdoIgetthenumberofelementsinalistinPython? 2018 HowdoIcounttheoccurrencesofalistitem? HotNetworkQuestions Constructing\newcommandwithcaret('^')orunderscore('_') HowdoChristiansrespondtothecriticismthatJesusofNazarethdidnotbringworldpeace? Areaerialtankersconvertedaircraftortheirowndesigns? HowcanIdealwithalawyerwhoisignoringtherealclientinfavorofthetechnicalclient? Thesecondevensublimenumber Canyouputapropelleronthebackofaplane,andhaveitgoforward? Isitascamifsomeoneasksformyfullname,email,andbankname? Discbrakessometimessing Doplanetsloseenergywhilerotating? CanIreplace'havenot'or'haven't'with'ain't'inoralEnglish? Whatwouldbethebestareaofmedicineforadoctorthatmoonlightsinfightingeviltospecializetheircareerintodealwithunexplainedabsences? ImprovedSieveofEratosthenes WhywouldthepriestsbribeguardstoliewhengivenclearevidencethatJesuswasimmortal?(Mt.28:11-12) Galatians4:14.PaulsaysthatJesusisAngeloftheLord? DifferentiatingBellmanequation HowcanImonitormyrooftodetectroofleaksbeforetheycausedamage? StartabatfileonremotePC TheFirstPublishedbookonAlgebraicTopology 25PINsound/gameribboncable Ispronouncingloanwordsaccordingtotheir"native"pronunciationstigmatisedacrossmostculturesandlanguages? InwhatWesternCountrieshasanypartyorcoalitionbeenelectedgainingasupermajorityorsuchmajoritypermittingconstitutionalamendments? DoesarangerwiththeLand'sStridefeatureignoredamagefromtheSpikeGrowthspell? Whydophotoswithdifferentsettingsproducedifferentspots? Feelingguiltyaboutbeingsecondauthor morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1Get a list of numbers as input from the user - python
In Python 3.x, use this. a = [int(x) for x in input().split()]. Example. >>> a = [int(x) for x in...
- 2Python Get a list as input from user - Tutorialspoint
We can also use input function twice so that we can create a list of lists. Use the range functio...
- 3[Day03]Python的基本運算!(上) - iT 邦幫忙
input()不管輸入什麼都是返回字串哦這點要注意! 匯入模組import. 使用import匯入需要的模組,通常我們會寫在程式的最上方。
- 4How To Input A List In Python - Edureka
This article will introduce you to different ways to input a list in Python and give you a detail...
- 5How To Input a List in Python - Besant Technologies
How to Input a list in python? ... The list is one of the data structure in python. It is basical...