Главная » Просмотр файлов » Josh Cogliati - Non-Programmers Tutorial For Python

Josh Cogliati - Non-Programmers Tutorial For Python (779876), страница 9

Файл №779876 Josh Cogliati - Non-Programmers Tutorial For Python (Josh Cogliati - Non-Programmers Tutorial For Python) 9 страницаJosh Cogliati - Non-Programmers Tutorial For Python (779876) страница 92018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 9)

The second to the last is index -2 and so on. Here are some more examples:>>> list[len(list)-1]’five’>>> list[len(list)-2]’four’>>> list[-1]’five’>>> list[-2]’four’>>> list[-6]’zero’Thus any item in the list can be indexed in two ways: from the front and from the back.Another useful way to get into parts of lists is using slices. Here is another example to give you an idea what they canbe used for:61>>> list = [0,’Fred’,2,’S.P.A.M.’,’Stocking’,42,"Jack","Jill"]>>> list[0]0>>> list[7]’Jill’>>> list[0:8][0, ’Fred’, 2, ’S.P.A.M.’, ’Stocking’, 42, ’Jack’, ’Jill’]>>> list[2:4][2, ’S.P.A.M.’]>>> list[4:7][’Stocking’, 42, ’Jack’]>>> list[1:5][’Fred’, 2, ’S.P.A.M.’, ’Stocking’]Slices are used to return part of a list.The slice operator is in the formlist[first_index:following_index].

The slice goes from the first_index to the index beforethe following_index. You can use both types of indexing:>>> list[-4:-2][’Stocking’, 42]>>> list[-4]’Stocking’>>> list[-4:6][’Stocking’, 42]Another trick with slices is the unspecified index. If the first index is not specified the beginning of the list is assumed.If the following index is not specified the whole rest of the list is assumed.

Here are some examples:>>> list[:2][0, ’Fred’]>>> list[-2:][’Jack’, ’Jill’]>>> list[:3][0, ’Fred’, 2]>>> list[:-5][0, ’Fred’, 2]Here is a program example (copy and paste in the poem definition if you want):62Chapter 13. More on Listspoem = ["<B>","Jack","and","Jill","</B>","went","up","the","hill","to","<B>",\"fetch","a","pail","of","</B>","water.","Jack","fell","<B>","down","and",\"broke","</B>","his","crown","and","<B>","Jill","came","</B>","tumbling",\"after"]def get_bolds(list):true = 1false = 0## is_bold tells whether or not the we are currently looking at## a bold section of text.is_bold = false## start_block is the index of the start of either an unbolded## segment of text or a bolded segment.start_block = 0for index in range(len(list)):##Handle a starting of bold textif list[index] == "<B>":if is_bold:print "Error: Extra Bold"##print "Not Bold:",list[start_block:index]is_bold = truestart_block = index+1##Handle end of bold text##Remember that the last number in a slice is the index## after the last index used.if list[index] == "</B>":if not is_bold:print "Error: Extra Close Bold"print "Bold [",start_block,":",index,"] ",\list[start_block:index]is_bold = falsestart_block = index+1get_bolds(poem)with the output being:BoldBoldBoldBold[[[[1 : 4 ] [’Jack’, ’and’, ’Jill’]11 : 15 ] [’fetch’, ’a’, ’pail’, ’of’]20 : 23 ] [’down’, ’and’, ’broke’]28 : 30 ] [’Jill’, ’came’]The get_bold function takes in a list that is broken into words and token’s.

The tokens that it looks for are <B>which starts the bold text and <\B> which ends bold text. The function get_bold goes through and searches for thestart and end tokens.The next feature of lists is copying them. If you try something simple like:63>>>>>>>>>[1,>>>>>>[1,>>>[1,a = [1,2,3]b = aprint b2, 3]b[1] = 10print b10, 3]print a10, 3]This probably looks surprising since a modification to b resulted in a being changed as well. What happened is thatthe statement b = a makes b a reference to a.

This means that b can be thought of as another name for a. Henceany modification to b changes a as well. However some assignments don’t create two names for one list:>>>>>>>>>[1,>>>[1,>>>>>>[1,>>>[1,a = [1,2,3]b = a*2print a2, 3]print b2, 3, 1, 2, 3]a[1] = 10print a10, 3]print b2, 3, 1, 2, 3]In this case b is not a reference to a since the expression a*2 creates a new list.

Then the statement b = a*2 givesb a reference to a*2 rather than a reference to a. All assignment operations create a reference. When you pass a listas a argument to a function you create a reference as well. Most of the time you don’t have to worry about creatingreferences rather than copies. However when you need to make modifications to one list without changing anothername of the list you have to make sure that you have actually created a copy.There are several ways to make a copy of a list. The simplest that works most of the time is the slice operator since italways makes a new list even if it is a slice of a whole list:>>>>>>>>>>>>[1,>>>[1,a = [1,2,3]b = a[:]b[1] = 10print a2, 3]print b10, 3]Taking the slice [:] creates a new copy of the list.

However it only copies the outer list. Any sublist inside is still areferences to the sublist in the original list. Therefore, when the list contains lists the inner lists have to be copied aswell. You could do that manually but Python already contains a module to do it. You use the deepcopy function ofthe copy module:64Chapter 13. More on Lists>>> import copy>>> a = [[1,2,3],[4,5,6]]>>> b = a[:]>>> c = copy.deepcopy(a)>>> b[0][1] = 10>>> c[1][1] = 12>>> print a[[1, 10, 3], [4, 5, 6]]>>> print b[[1, 10, 3], [4, 5, 6]]>>> print c[[1, 2, 3], [4, 12, 6]]First of all notice that a is an array of arrays.

Then notice that when b[0][1] = 10 is run both a and b are changed,but c is not. This happens because the inner arrays are still references when the slice operator is used. However withdeepcopy c was fully copied.So, should I worry about references every time I use a function or =? The good news is that you only have to worryabout references when using dictionaries and lists. Numbers and strings create references when assigned but everyoperation on numbers and strings that modifies them creates a new copy so you can never modify them unexpectedly.You do have to think about references when you are modifying a list or a dictionary.By now you are probably wondering why are references used at all? The basic reason is speed.

It is much faster tomake a reference to a thousand element list than to copy all the elements. The other reason is that it allows you tohave a function to modify the inputed list or dictionary. Just remember about references if you ever have some weirdproblem with data being changed when it shouldn’t be.6566CHAPTERFOURTEENRevenge of the StringsAnd now presenting a cool trick that can be done with strings:def shout(string):for character in string:print "Gimme a "+characterprint "’"+character+"’"shout("Lose")def middle(string):print "The middle character is:",string[len(string)/2]middle("abcdefg")middle("The Python Programming Language")middle("Atlanta")And the output is:Gimme a L’L’Gimme a o’o’Gimme a s’s’Gimme a e’e’The middle character is: dThe middle character is: rThe middle character is: aWhat these programs demonstrate is that strings are similar to lists in several ways.

The shout procedure shows thatfor loops can be used with strings just as they can be used with lists. The middle procedure shows that that stringscan also use the len function and array indexes and slices. Most list features work on strings as well.The next feature demonstrates some string specific features:67def to_upper(string):## Converts a string to upper caseupper_case = ""for character in string:if ’a’ <= character <= ’z’:location = ord(character) - ord(’a’)new_ascii = location + ord(’A’)character = chr(new_ascii)upper_case = upper_case + characterreturn upper_caseprint to_upper("This is Text")with the output being:THIS IS TEXTThis works because the computer represents the characters of a string as numbers from 0 to 255.

Python hasa function called ord (short for ordinal) that returns a character as a number. There is also a corresponding function called chr that converts a number into a character. With this in mind the program should startto be clear. The first detail is the line: if ’a’ <= character <= ’z’: which checks to see if a letter is lower case. If it is than the next lines are used. First it is converted into a location so that a=0,b=1,c=2and so on with the line: location = ord(character) - ord(’a’).

Next the new value is found withnew_ascii = location + ord(’A’). This value is converted back to a character that is now upper case.Now for some interactive typing exercise:68Chapter 14. Revenge of the Strings>>> #Integer to String...>>> 22>>> repr(2)’2’>>> -123-123>>> repr(-123)’-123’>>> #String to Integer...>>> "23"’23’>>> int("23")23>>> "23"*2’2323’>>> int("23")*246>>> #Float to String...>>> 1.231.23>>> repr(1.23)’1.23’>>> #Float to Integer...>>> 1.231.23>>> int(1.23)1>>> int(-1.23)-1>>> #String to Float...>>> float("1.23")1.23>>> "1.23"’1.23’>>> float("123")123.0If you haven’t guessed already the function repr can convert a integer to a string and the function int can converta string to an integer.

The function float can convert a string to a float. The repr function returns a printablerepresentation of something. Here are some examples of this:>>> repr(1)’1’>>> repr(234.14)’234.14’>>> repr([4,42,10])’[4, 42, 10]’The int function tries to convert a string (or a float) into a integer. There is also a similar function called floatthat will convert a integer or a string into a float. Another function that Python has is the eval function. The eval69function takes a string and returns data of the type that python thinks it found.

For example:>>> v=eval(’123’)>>> print v,type(v)123 <type ’int’>>>> v=eval(’645.123’)>>> print v,type(v)645.123 <type ’float’>>>> v=eval(’[1,2,3]’)>>> print v,type(v)[1, 2, 3] <type ’list’>If you use the eval function you should check that it returns the type that you expect.One useful string function is the split function. Here’s the example:>>> import string>>> string.split("This is a bunch of words")[’This’, ’is’, ’a’, ’bunch’, ’of’, ’words’]>>> string.split("First batch, second batch, third, fourth",",")[’First batch’, ’ second batch’, ’ third’, ’ fourth’]Notice how split converts a string into a list of strings.

Характеристики

Тип файла
PDF-файл
Размер
201,87 Kb
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6294
Авторов
на СтудИзбе
314
Средний доход
с одного платного файла
Обучение Подробнее