На первый взгляд, язык Python может показаться непривычным для разработчиков Java. Было бы неплохо посмотреть, как Python выполняет простые задачи, с которыми мы сталкиваемся при работе с другими языками, такими как Java. Простые фрагменты кода мы называем «шпаргалки». Чтение шпаргалок в языке программирования – это очень полезно, и может помочь новичкам в изучении. Обратите внимание на то, что кроме кода, указанных в данной статье существует великое множество других шпаргалок — предложите в комментариях свой вариант шпаргалок которые вы часто используете.
*Учтите: порядок списка не отображает популярность шпаргалок
Фильтр списка
Python# Фильтр пустых строк в списке строк.list = [x for x in list if x.strip()!=»]12# Фильтр пустых строк в списке строк.list = [x for x in list if x.strip()!=»]
Чтения файла по строкам
Pythonwith open(«/path/to/file») as f: for line in f: print(line)123with open(«/path/to/file») as f: for line in f: print(line)
Запись в файл строкой за строкой
Pythonf = open(«/path/tofile», ‘w’)for e in aList: f.write(e + «n»)f.close()123456f = open(«/path/tofile», ‘w’) for e in aList: f.write(e + «n») f.close()
(adsbygoogle = window.adsbygoogle || []).push({});
Позиционирование строки в тексте
Pythonsentence = «this is a test, not testing.»it = re.finditer(‘\btest\b’, sentence)for match in it: print(«match position: » + str(match.start()) +»-«+ str(match.end()))1234sentence = «this is a test, not testing.»it = re.finditer(‘\btest\b’, sentence)for match in it: print(«match position: » + str(match.start()) +»-«+ str(match.end()))
Поиск используя регулярные выражения
Pythonm = re.search(‘d+-d+’, line) # search 123-123 like stringsif m: current = m.group(0)123m = re.search(‘d+-d+’, line) # search 123-123 like stringsif m: current = m.group(0)
Запрос в базе данных
Pythondb = MySQLdb.connect(«localhost», «username», «password», «dbname»)cursor = db.cursor()sql = «SELECT `name`, `age` FROM `ursers` ORDER BY `age` DESC»cursor.execute(sql)results = cursor.fetchall() for row in results: print(row[0] + row[1]) db.close()1234567891011db = MySQLdb.connect(«localhost», «username», «password», «dbname»)cursor = db.cursor() sql = «SELECT `name`, `age` FROM `ursers` ORDER BY `age` DESC»cursor.execute(sql)results = cursor.fetchall() for row in results: print(row[0] + row[1]) db.close()
[vc_row][vc_column width=»1/3″ css=».vc_custom_1600070905017{background-color: #81d742 !important;}»][vc_icon icon_fontawesome=»fa fa-question-circle» color=»green» background_style=»rounded» size=»lg» align=»center»][vc_column_text]
Есть вопросы по Python?
На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!
[/vc_column_text][vc_btn title=»Python Форум Помощи» color=»mulled-wine» align=»center» i_icon_fontawesome=»fa fa-share-square-o» button_block=»true» add_icon=»true» link=»url:https%3A%2F%2Fitfy.org%2F||target:%20_blank|rel:nofollow»][/vc_column][vc_column width=»1/3″ css=».vc_custom_1600071246022{background-color: #eeee22 !important;}»][vc_icon icon_fontawesome=»fa fa-telegram» color=»sky» background_style=»rounded» size=»lg» align=»center»][vc_column_text]
Telegram Чат & Канал
Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!
[/vc_column_text][vc_row_inner][vc_column_inner width=»1/2″][vc_btn title=»Чат» color=»sky» align=»center» i_icon_fontawesome=»fa fa-comments» button_block=»true» add_icon=»true» link=»url:https%3A%2F%2Ftelegram.im%2F%40python_scripts%3Flang%3Dru||target:%20_blank|rel:nofollow»][/vc_column_inner][vc_column_inner width=»1/2″][vc_btn title=»Канал» color=»sky» align=»center» button_block=»true» link=»url:https%3A%2F%2Ftelegram.im%2F%40pip_install%3Flang%3Dru||target:%20_blank|rel:nofollow»][/vc_column_inner][/vc_row_inner][/vc_column][vc_column width=»1/3″ css=».vc_custom_1600071543031{background-color: #27cbf4 !important;}»][vc_icon icon_fontawesome=»fa fa-vk» color=»peacoc» background_style=»rounded» size=»lg» align=»center»][vc_column_text]
Паблик VK
Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!
[/vc_column_text][vc_btn title=»Подписаться» color=»violet» align=»center» i_icon_fontawesome=»fa fa-vk» button_block=»true» add_icon=»true» link=»url:https%3A%2F%2Fvk.com%2Fopen_sourcecode||target:%20_blank|rel:nofollow»][/vc_column][/vc_row]window.yaContextCb.push(()=>{ Ya.Context.AdvManager.render({ renderTo: ‘yandex_rtb_R-A-457373-16’, blockId: ‘R-A-457373-16’ })})
Соединение списка с указанным символом
PythontheList = [«a»,»b»,»c»]joinedString = «,».join(theList)12theList = [«a»,»b»,»c»]joinedString = «,».join(theList)
Фильтр дублируемых элементов
PythontargetList = list(set(targetList))1targetList = list(set(targetList))
Удаляем пустые значения из списка
PythontargetList = [v for v in targetList if not v.strip()==»]# илиtargetList = filter(lambda x: len(x)>0, targetList)123targetList = [v for v in targetList if not v.strip()==»]# илиtargetList = filter(lambda x: len(x)>0, targetList)
Добавление списка к другому списку
PythonanotherList.extend(aList)1anotherList.extend(aList)
Итерация словаря
Pythonfor k,v in aDict.iteritems(): print(k + v)12for k,v in aDict.iteritems(): print(k + v)
Есть ли строка в списке
PythonmyList = [‘one’, ‘two’, ‘ten’]if ‘one’ in myList: print(‘Да’)1234myList = [‘one’, ‘two’, ‘ten’] if ‘one’ in myList: print(‘Да’)
window.yaContextCb.push(()=>{ Ya.Context.AdvManager.render({ renderTo: ‘yandex_rtb_R-A-457373-3’, blockId: ‘R-A-457373-3’ })})
Соединяем два словаря
Pythonx = {‘a’: 1, ‘b’: 2}y = {‘b’: 3, ‘c’: 4}z = {**x, **y}print(z) # {‘c’: 4, ‘a’: 1, ‘b’: 3}123456x = {‘a’: 1, ‘b’: 2}y = {‘b’: 3, ‘c’: 4} z = {**x, **y} print(z) # {‘c’: 4, ‘a’: 1, ‘b’: 3}
В данном списке приведены далеко не все идиомы Python.
Оставляйте свои варианты в комментариях!