text:
AннотацияВесомым достижением «антропологического поворота» философской мысли XIX-XX вв., а также современной социологии, теории права и др. дисциплин является разработка идеи и образа человеческого достоинства как ценностно-мировоззренческого основания социального развития, преодоления конфликтных ситуаций в обществе. Имплицитные противоречия современных концепций достоинства человека (неразработанность природы достоинства, совмещение достоинства с оценкой, примат деятельностного подхода и др.) затрудняют имплементацию принципа достоинства как регулятива социальной практики. Необходима новая (конструктивная) теория достоинства, которая должна прийти на смену дескриптивным подходам и призвана синтезировать идею и образы человеческого достоинства в единый рационально-ценностный и эмоциональный комплекс, поддерживаемый механизмами самосознания личности и человеческого сообщества, и в частности, рефлексией достоинства.
Ключевые слова: человеческое достоинство, деятельностный подход, дескриптивная концепция достоинства, конструктивная концепция достоинства, самовосприятие, интроспекция, самопонимание, рефлексия достоинства
К сожалению, текст статьи доступен только на Английском
1. Introduction
Latest developments in post-Soviet space as well as in the Mid-East area, especially the Ukrainian crisis and the atrocities of the "Islamic state", demonstrate how acute is the risk of rapid dehumanization, massive violence in the course of civil conflict. Despite the thorough theoretical work over the concepts and value complexes of humanism, mutual understanding, non-violence etc. in modern philosophy, sociology, conflictology, ethical studies, these concepts to a considerable extent fail to serve as landmarks and moral criteria of social life.
Contemporary humanities are still in need of some pivotal idea or concept that would be based on a solid philosophic and argumentative ground, would be in correspondence with traditional religious outlook and values and would also possess a developed system of theoretic and pragmatic implications, moral and emotional supplements that would hopefully stop the humanity from avalanche-like beastification. One of such concepts that has the peculiar tradition of problematization and at the same time deserves a more thorough transdisciplinary approach is the idea and notion of human dignity.
Theoretical arrangement associated with this idea is one of the most significant achievements of the "anthropological turn" in post-classical philosophy. At the same contemporary tradition in the understanding of human dignity inherits the spirit and topical fields of reasoning dignity in Plato's, Aristotle's and the stoics' teachings, and reflects certain traits of Renaissance humanism, French Enlightenment and of course the German transcendental school. In the meanwhile, it was merely the post-classic era that established the possibility to argue that the idea of dignity and its theoretic definitions must be supplemented with a deliberate imagery of dignity to become the true and effective regulation of social life.
2. Research findings
Deliberating the idea and image of dignity, post-classical philosophy does close a sort of historical "circle". In ancient philosophy, we start with a visual demonstration of dignity in the mindset and "modus vivendi" of a thoroughly thinking (philosophizing) person. Over time, we come to the idea, typical for Modern-era thought, that dignity is a theoretical principle, rational basis of life and human interaction. Dignity as a principle fits into the concept of the "world as it must" necessary for the expedient transformation of the "world that is". Finally, the post-classical philosophy, from Schopenhauer and Nietzsche to the existentialists and Marxists, speaks of dignity as precisely the ability to synthesize the idea and the image, to embody the intelligible principle in the practice, seeking to convert, organize, subordinate to the moral law chaotic, often absurd, unjust or inauthentic world. Dignity is therefore more than a principle and more than a behavioral trait: it is merely the human capacity for responsibility (first of all, to the self) and for "wholeness" of life provided by (and supplied with) the internal moral law, the criterion of right and justice.
One may say that such understanding of dignity is not exclusively "humanitarian" anymore. It can be interpreted broadly – as far as to say that dignity is in general a quality of a structural unit in a system of relations mediated by symbolic exchange, such as communication mediated by values. Such dignity is an attribute of person (merely a person capable of communicating and cooperating with others and at the same time of deliberate isolation from them) but may also be a sign of a cultural phenomenon, an ideology, a scientific discipline or a teaching. No wonder that the modern Russian researcher A. Bikbov entitled his essay in the sociology of philosophical knowledge (or exactly on how philosophers promote themselves in the scientific community) «Philosophical dignity as an object of study» [1]. And for example Harvard professor M. Rosen in his book "The dignity of history and meaning" [2] analyzes dignity as a concept entwined in the disciplinary and cultural ties, including philosophy, law, politics, ethics, theology and specific religious beliefs. Moreover, he sees dignity as a means of clarifying the legal, political, ethical and religious discourse by placing it in a particular social context.
Below, we will still focus on the most obvious mode of dignity – the dignity of the human being. Post-classical humanities boast rich variety of paradigms of the human in which notions of human dignity are also different. In particular, we may notice the similarities and differences between the existential-phenomenological philosophy, which perceives through the German neo-Kantianism essential features of Kant's approach to the phenomenon of humanity, and socio-critical tradition (including neo-Marxism and post-Marxism), focused on the distinction between true and alienated human existence. Substantial contribution to the understanding of the dignity is made by structuralism and post-structuralism, with its attention to symbolic determinants of self-identification.
For contemporary Russian authors, it is typical to understand dignity as "a characteristic of a person from the standpoint of his intrinsic value, correspondence to one's predestination" [3]. This definition unveils the paradox: to what extent can we talk about "predestination" of a person having not determined the ontological grounds of his dignity (and of his, to say so, "destiny" as well)? And if we even put such goal before ourselves, doesn't it mean that the ontology of dignity relies on the notion of "predestination" as some transcendental condition, irrational entity, something like "αμαγκη" or "dao"?
To circumvent this difficulty, post-classic thought states that the source of dignity is to be searched for in no impersonal environment but in the ontology of individual. Under this approach, we would rather replace "predestination" with "vocation" and thus get the notion of dignity as thinking, behavior and values of the self-actualizing personality. Self-actualized people, – says A. Maslow – involve into something that is outside themselves. They are committed to this business, it is something very valuable to them – a kind of vocation (see: [4, p. 110]). From here follows the idea of the activity-related nature of human dignity: it is not a prerequisite of human existence, but above all the opportunity and goal. Human activity that meets certain criteria does objectifiy and event thingify dignity; thereby the activity itself acquires the status of worthiness. On the other hand, the lack of activity is sometimes harmful for dignity.
Linking the ideas of human dignity and activity, we see that in post-classical conceptual contexts dignity appears in two ways: first, as a phenomenon (a feature of a person, an integral indicator of one's self-understanding and self-perception), and then, as a principle (an essential trait of human co-existence, enclosing an imperative of behavior). It is important that dignity involves not only the self-determination in social reality (the latter is always given to a person in a certain view and implicitly guides the mind in a certain direction), but also in the wider frame of reference. This is self-identification within history, in politics and culture, in the context framed by the image of "all mankind", the sense of humanity and its destiny. That's probably why Kant spoke of the value constitution of culture due to the fact that the existence of values as such is only possible by virtue of the human relationship to the world, "as a measure of humanity and freedom" (see: [5, p. 7]), and "morality, and humanity as capable of it, is that which alone has dignity" [6, p. 212].
Apart from them the mentioned "predestination paradox", which is more or less eliminable by the activity approach, some more difficulties exist.
First, it is the question of nature and (or) socio-historic and anthropological genesis of human dignity and rights, dialectics of their relations. Activity approach is the attitude that merely unites the question of dignity with the problem of human rights. In other words, the notion human rights gets its precise sense due to the fact that the human being, representing activity, involves in communication, cooperation and possible contradiction with the other. Still, as M. Rosen notes, attention to human rights does not only make the problem of dignity more distinctive, but paradoxically draws attention away from the non-codified right of some other nature – the right to perception and acknowledgement of one's dignity in the other's mind, emotions and world-outlook (apart from what he or she is actually doing). In fact, the matter is of the "right to be respected", which derives from dignity and stands for premise of "worthy relation" to the other both in thought and deed.
In a most clear way this correspondence between dignity and rights is demonstrated by the "Statement of Ethical Principles" adopted by the International Federation of Social Workers. It is stated there that social work is based on the "…inherent worth and dignity of all people, and the rights that follow from this" [7]. This is quite a bold declaration, because dignity is not just mentioned along with the rights, but is uniquely determined as a source of rights (hence there's only one step to the understanding of dignity as a source of law in general).
Dignity is often described as the human's constant attribute. But, as R. Apresian in particular argues, the idea of dignity forms in the course of history as not exactly as estimative but more as an imperative characteristic. Human being is granted dignity (this is the attitude of Christianity in private) and he must be worthy of this divine gift. Thus the notion of inherency of dignity intertwines with the notion of "endowment". The latter doesn't always necessarily mean possession, at least not the one we can explicitly state. S. Darwall writes that "although Kant sometimes conceives of dignity as involving a standing every person has to demand, or 'exact' respect, Kant also treats dignity as a value we can all achieve, but only when we properly exercise our capacity for moral choice" [8, p. 8]. As a result, dignity in contemporary thought is first of all potential of a human and a peculiar task for him, a test for the whole mankind. Not accidentally M. Heidegger emphasized that "higher humanistic definition of a human being has not yet reached the true dignity of man" [9, p. 328].
Another difficulty arises as the question about the scope of implementation of dignity as a principle. They sometimes speak about "dignity of human" and "dignity of person / personality" as of notions that differ in degree of generality. Sociological case studies introduce the idea of corporate, or group, dignity derived from the phenomenon of group solidarity and mutual coincidence of personal dispositions of members of the group (see: [10]). The concept of the "dignity of human life" evolve in the context of modern bioethics, etc.
Still more difficulties are caused by the necessity to introduce the idea of human dignity to the topical area of axiology. The Preamble of the United Nations Charter places into the one synonymous row "faith in fundamental human rights, in the dignity and worth of the human person, in the equal rights of men and women and in the equal rights of nations large and small". It is peculiar that "dignity and worth" act here as mutually supplementary attributes. The logic of the authors of the document is probably that it's scarcely enough to nominate respect for the individual through the "dignity" or "value" alone, but only through their synthesis.
There is certain history behind this thought. The idea of dignity is intertwined not only with the concept of value, but also with the idea of evaluation: that means to "evaluate" oneself, to look for evaluation (appreciation) from the other, to take an external estimate as adequate or abandon, to overcome it. Self-assessment of one's dignity, especially critical one, seemingly confers person to certain moral advantage or "power". And nevertheless, according to many philosophers of post-classical era, it is important to completely separate evaluation of dignity from the recognition of it. Even if a person is recognized in his / her dignity, not every such recognition is all right, for it can be even humbling, as when awarded conditionally («He is worthy because he is such a… / has done something…»). "It is time to understand, finally, that acknowledging something as "value" deprives the evaluated of its dignity, – M. Heidegger writes. – This means: because of assessing something as a value the estimated object begins to exist only as a subject of human evaluation" [9, p. 34-344].
But no matter how we try to protect the idea of "pure dignity" within its own theoretical field, in practice this approach is not quite applicable. As, for instance, J. Habermas notes, in actual problematic situations the sense of human dignity inevitably involves pragmatic connotations – not central, but certainly significant. They are connected with the idea of actually checkable value, primarily through the self-esteem of a person, but also in the context of assessments given by others. In philosophical and political discourse human dignity and its socially acceptable personality treats (some "personal achievements" or "merits") are quite often identified with each other. Based on this principle, in particular, the ideology of meritocracy, the origins of which are contained in the works of M. Young [11]. However attractive in itself, his ideas leave many questions in what concerns implementation. Their popularity testifies to the problem state of the political and legal identity of society, the discrepancy between self-esteem and its regulatory mechanisms, such as representative democracy. Even in a democratic society, and merely in it, "the appearance of meritocratic discourse that resembles that power should belong to the worthy is a sign of an impending crisis of legitimacy" [12].
The mentioned difficulty is driven by the effort of many thinkers and public figures to lead the idea of dignity out of the shadows on intuitive notion of "natural" hierarchy of merits as a system of more and less "worthy" social statuses. This is not an easy task to fulfill, because the status hierarchy, observable in the animal world as well, is apparently deeply rooted in the psyche of a human being. And still many modern social philosophers, say for instance J. Waldron and M. Dan-Cohen in their work "Dignity, Status and Rights", note that it is more productive to speak of dignity in terms of achieving equally high status for as much people than to abandon the discourse of statuses at all (see: [13]).
Here it should be mentioned again that activity approach is also related to understanding of human dignity as a source of social action and the basis of law. This approach is reflected in particular in the Article 1 of the Basic Law for the Federal Republic of Germany of 1949. It stated that the inviolability of human dignity and human rights is a peremptory basis "inviolable and inalienable human rights as the basis of every community, of peace and of justice in the world". More concise formulation is given in the Constitution of the Republic of Belarus (Art. 25 – "The state shall ensure the freedom, integrity and dignity of the person"), of the Constitution of the Russian Federation (Art. 31 – "Human dignity shall be protected by the state. Nothing can be the basis for its derogation"). Ultimately, modern researchers note: despite very different understandings of what is included in the set of inalienable human rights and to what divisions ("generations") they should be systematized, we find the point of convergence of multiple legal traditions and systems in the very understanding of what dignity is and how it should be protected. This implies that the dignity is in fact a catch-all category, even more applicable for understanding and dialogue between civilizations and legal cultures than "human rights" in their European sense.
We would specifically comment on the approach implemented in the Constitution of the Republic of Poland, where it is said that "the natural and inalienable dignity of the person is the source of rights and freedoms of human and citizen. It is inviolable and its respect for and protection are the responsibility of public authorities". The self-applying reflexive ratio is remarkable here: dignity is "the main motive and justification for the existence of rights and freedoms" [14], but the very notion of dignity is introduced primarily by reference to the rights and freedoms. One of the first who put these concepts in such a "reverse" order was J.-J. Rousseau, who famously remarked that "give up one's freedom means to renounce one's human dignity, abandon one's human rights and even his duties". Due to this ratio human dignity is often spoken of as primarily the civil dignity – readiness for civil action aimed at protecting one's and common rights.
But doesn't this in the long run imply that dignity is a metaphysic substance or a simulacrum of sort, always constantly appearing and being referred to in its otherness but having no own true being? To answer this partly provocative question we must mention the problem of "scope" or "limits" of human dignity at the conceptual, practical and reflexive level. The history of mankind gives us many examples of what can be called "acquisition" of dignity in thought, action, decision. It is easy to recall instances when frankly inhuman treatment did not deprive the victim of "inner core", which meant for him/her following the internal criteria of authenticity and correctness. But there are also numerous examples where people in similar circumstances demonstrated complete loss of such a criterion, so to say, betrayed themselves.
Search for some common rule in each of such cases determines the request for transition from descriptive concept of dignity to constructive one. Characteristic feature of the first is the description and interpretation of "dignity experience". The second focuses on the formulation of the decisive conditions of dignity, the transition from the experience of "non-esteem" to "dignity" and also (which surely cannot be omitted from study) from esteem back to indignity. Samples of the descriptive approach are there in the theories of G. Pico della Mirandola, B. Pascal, in post-classical era – for instance, in H. Bergson's works. The constructive approach derives primarily from the works of I. Kant. Among the thinkers who sought to follow this pattern in post-classical era was M. Heidegger with his idea of dignity as "putting the humanity at the service of man". Echoes of this idea can be heard particularly in the theory of L. Fuller who talks about the "inner morality of law", which implies such qualities of legislation as clarity, consistency, immutability of the language, the orientation for the future. Dignity should therefore be seen not just as a prerequisite for the law, but also as a criterion of "effective humanism" of legislation. A theory based on the constructive concept of dignity would describe the principles of activity, communication, management that would make human dignity true regulation of social life.
Relying on considerations that have been given about the image and idea of human dignity, can we formulate the most crucial requirements for the constructive theory of human dignity?
First of all, such theory should be formulated on the basis of the analysis of peculiar cognitive-and-value environment in which dignity grows, especially the analysis of dignity-value complex. This environment is in fact nothing but self-consciousness or self-awareness of a personality, a social group, a nation.
Merely in the context of self-consciousness dignity ceases to be perceived as an abstract goal, or some transcendentalia. Instead, it can be mastered as an important motive of concrete actions of personal, professional and primarily sociopolitical scope. Mind the eloquent citation from V. Stolin's work: "As phenomena of consciousness, duty, responsibility, honor, dignity, conscience… concretize for social individual... such moral values… as good, justice, and humanity. These phenomena are… a form of expression of the most important feature of the motivational sphere of the human, because they relate to the fact that with their highest moral content these motives lead outside his individual existence… and connect with the problems of epoch, of society in a whole" [15]. Not by chance the most advanced human rights codes historically evolved in those cultures where the matrix of philosophical understanding of the world and human's place in it used to rest on the idea of sovereignty of self, on special ontological status of the active subject.
Second, identifying of dignity should be based on the understanding of relations between the idea and the image. For that sake the constructive theory of dignity must in its own turn differentiate modes (or levels) of self-consciousness. It is justified to consider at least three of them: self-perception, introspection and self-understanding.
At the self-perception level dignity is represented as a special mode to relation to the self; a personal or a collective setting on self-esteem connected with posting some certain moral requirement or criteria to the self. This process involves the formation of a stable self-esteem stemming from a fairly rigid, sometimes critical, self-assessment and internal design of measures to improve it, that is some "working on self".
At the introspection level (mind that we should not mix this with psychological introspection which means registering changes in one's emotions or thoughts) through witnessing the process of self-esteem growing, its variations and crises, a person primarily generalizes one's image of dignity to become an idea or concept. The latter then can act as the integral principle of evaluating both the self and the others. In other words, the feeling of dignity transforms in some conceptual definition of dignity, possessing a repertoire of verbal and image connotations. In a personal scale this generalization can bear expressive emotional and aesthetic coloring (evaluation of actions in terms of "beauty", "style", etc.). In a group scale it is also implemented in the artistic, fiction discourse filled with symbols and allegories of qualities preferred for this community.
At the self-understanding level the separate verbal definitions and figurative connotations of human dignity fit into the conceptual structure of dignity as a universal principle applicable for the design of large-scale forms of personal, social, group, national, civilizational development. It is undoubtedly the most complex level, because on its way to the universal principle the idea of dignity should, in a sense, escape from the close interconnectedness with a repertoire of images, but not to stay in this bloodless theoretical formula.
Third, what must provide an increase in self-awareness in the transition to still higher level is the reflection of dignity. Its theoretical expression should be such a structural concept, in which the idea of dignity-values does not substantiate it in private images, "cases", examples, but stays significant and justified in itself, and at the same time embodies in visual images, eloquent stories, parables etc. needed for educational work.
3. Conclusions
Constructive theory of dignity should surely take into account the benefits of the activity approach, while avoiding its limitations. Human dignity cannot be reduced to its readiness to fulfill social functions. Universal correlate of human dignity could be generalized as a notion of the human person as the creator of history, civilization and culture, the "author" of a set of good and useful artifacts that fill the life-world of mankind: from stone tools to the modern technologies. It means that the activity approach developed by contemporary philosophic anthropology and other disciplines can be modified with the reference to the concept of human creativity. Human dignity is increasingly provided by the creative potential of the whole mankind, its ability to find adequate answers to the global and local challenges, to demonstrate movement to a more equitable, harmonious social and socio-natural world.
Thus, the theory of human dignity is no longer a derivative, side branch of a philosophical of sociological doctrine. On the contrary, the discourse of dignity often serves as some tool for adjusting a doctrine, some kind of "test for humanity". The problem of dignity in its modern interpretation does not imply a purely conceptual, theoretical solution but focuses on the development of syntetic approaches involving law, sociological, anthropological, medical, psychological and pedagogical knowledge, relevant forms and methods of educational work, and art, technology, public communications as well.
Список литературы
- Bikbov А. Philosophical Dignity as an Object of Study // Logos. 2004. № 3-4.
- Rosen M. Dignity, its History and Meaning. Harward University Press, 2012.
- Apresian R. Dignity // New Philosophic Encyclopedia: In 4 volumes / Ed. by. V. Stiopin, A. Huseinov, A. Ogurtsov, G. Semigin. М., 2000.
- Maslow А. Self-Actualization // Psychology of Personality. Texts. М., 1982.
- Stolovich, L.N. Kant on the problem of value // Kantian collection. 2009. № 2. Pp. 20-30.
- Kant I. Fundamental Principles of the Metaphysic of Morals / Works: in 8 vol. V. 4. М., 1994.
- Statement of Ethical Principles // International Federation of Social Workers [Electronic resource]. – URL: http://ifsw.org/policies/statement-of-ethical-principles (date of access: March 14, 2015)
- Darwall S. Honor, History, and Relationship: Essays in Second-Personal Ethics II. Oxford Scholarship Press, 2013.
- Heidegger M. Letter on Humanism // Problem of the Human in Western Philosophy: Translations / Comp. and afterword by P.S. Gurevich; tot. ed. Yu.P. Popov. М., 1988.
- Prusak А.I. Personal Dignity in Sociological Discourse // Socis. 2006. № 7.
- Young М. The Rise of the Meritocracy // Utopia and utopic consciousness / Comp. and tot. ed. V.A. Chalikova. М., 1991.
- Kustariov A. Meritocracy and Democracy // Emergency store [= Неприкосновенный запас]. 2013. №1.
- Waldron J., Dan-Cohen M. Dignity, Rank and Rights. Oxford Scholarship Press, 2012.
- Kovalyov А.А. Value and Dignity of Person – Philosophic and Legal Basis of Human Rights and Freedoms // Science and education: economy; business, law and management. 2011. № 2 [Electronic resource]. – URL: http://www.journalnio.com/ index.php?option=com_content&view=article&id=1097&Itemid=114. (date of access: March 14, 2015)
- Stolin V.N. Personal self-consciousness. М., 1983 [Electronic resource]. – URL: http://psylib.org.ua/ books/ stolv01/ txt10.htm. (date of access: March 14, 2015)


text:
Python is a cross platform computer programming language. It is an object-oriented dynamic type language. Notes include the basic skills of compiling and installing python, python list, dictionary, tuple, file operation and other commands.
◆ compiling and installing Python
Python development environment installation and configuration is very simple. If it is a Linux system, python environment will be integrated and installed by default. Python executable files are placed in the / usr/local/bin directory, and library functions are installed in the / usr/local/python directory. Because binary installation is not easy, the source code will be used to compile and install Python interpreter
1. First install the gcc compiler and the dependent packages needed to compile Python
[root@localhost ~]# yum -y install gcc zlib zlib-devel openssl openssl-devel libffi-devel wget Package gcc-4.8.5-36.el7.x86_64 already installed and latest version Package zlib-1.2.7-18.el7.x86_64 already installed and latest version Package zlib-devel-1.2.7-18.el7.x86_64 already installed and latest version Package openssl-1.0.2k-16.el7.x86_64 already installed and latest version Package openssl-devel-1.0.2k-16.el7.x86_64 already installed and latest version Package libffi-devel-3.0.13-18.el7.x86_64 already installed and latest version Nothing to do
2. Download Python source code, and execute nmake command in turn to complete the whole compilation process. If the waiting time is long, skip it
[root@localhost ~]# yum install -y readline [root@localhost ~]# wget https://www.python.org/ftp/python/3.8.0/Python-3.8.0.tgz [root@localhost ~]# tar -xzvf Python-3.8.0.tgz -C /usr/src/ [root@localhost ~]# cd /usr/src/Python-3.8.0/ [root@localhost ~]# ./configure --prefix=/usr/local/python3 [root@localhost ~]# make && make altinstall
3. Copy the python header file to the system standard directory to avoid that you can't find the required header file when using Python directly
[root@localhost ~]# cd /usr/local/python3/include/python3.8 [root@localhost ~]# cp -a ./* /usr/local/include/
4. Then we backup the old version of Python and create a symbolic link to the new version
[root@localhost ~]# cd /usr/bin/ [root@localhost bin]# mv python python.old [root@localhost bin]# ln -s /usr/local/python3/bin/python3.8 /usr/local/bin/python [root@localhost bin]# cp -a /usr/local/python3/bin/python3.8 /usr/bin/python
5. Because YUM warehouse is developed in Python, it needs to be replaced here to avoid the conflict between Python 2 and python 3
[root@localhost ~]# vim /usr/bin/yum #! / usr/bin/python2.7 ← change Python to python2.7 here [root@localhost ~]# vim /usr/libexec/urlgrabber-ext-down #! / usr/bin/python2.7 ← change Python to python2.7 here
6. Finally, test whether the new Python version is effective, and then use the YUM command to see whether it is effective. Everything is normal here
[root@localhost bin]# python Python 3.8.0 (default, Nov 9 2019, 01:48:59) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> exit()
7. Install the pip package management tool, which provides the functions of finding, downloading, installing and uninstalling Python packages
[root@localhost ~]# curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py [root@localhost ~]# python get-pip.py [root@localhost ~]# echo "alias pip=\"/usr/local/python3/bin/pip\"" >> /etc/profile [root@localhost ~]# pip --version pip 19.3.1 from /usr/local/python3/lib/python3.8/site-packages/pip (python 3.8)
Package Python as EXE: we install the pyinstaller tool to see if we can package independent executable files
[root@localhost ~]# pip install pyinstaller [root@localhost ~]# pip show pyinstaller [root@localhost ~]# pyinstaller -F ./lyshark.py [root@localhost ~]# pyinstaller -F -w -i lyshark.ico lyshark.py # -w: do not prompt the console
Compile Python to exe: you can compile Python to exe executable program by using python. Note that compilation is not packaging
C:/> python -m cython -3 --embed -o lyshark.c lyshark.py C:/> cl /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -I"D:\python\include" /Tc lyshark.c /DWIN32 C:/> link lyshark.obj /SUBSYSTEM:CONSOLE /MACHINE:X64 /LIBPATH:"D:\python\libs" C:/> link lyshark.obj /SUBSYSTEM:WINDOWS /MACHINE:X64 /LIBPATH:"D:\python\libs" /ENTRY:"wmainCRTStartup"
Compile Python to ELF: ELF is the file running format under Linux system. We can compile Python to ELF file
[root@localhost ~]# yum install -y epel-release [root@localhost ~]# yum install -y python-pip [root@localhost ~]# yum install -y python-dev* [root@localhost ~]# pip install cython [root@localhost ~]# cython lyshark.py --embed [root@localhost ~]# gcc `python-config --cflags` `python-config --ldflags` lyshark.c -o lyshark
◆ Python input and output
Input and output are the things that exist in any programming language. The essence of computer is input and output. Before learning python, you must first learn input and output. Python's input and output are very simple. If you input, you can directly use the input function. If you output, you can use the print function
Usage of standard input: the default reception is treated as a string. If you need a number, you need to cast it to int() to a number
>>> name = input("Please enter your name:") //Please enter your name: lyshark >>> print("Hello " + name) Hello lyshark >>> age = input("Please enter your age:") //Please enter your age: 22 >>> type(age) <class 'str'> >>> age1 = input("Please enter your age:") >>> age1 = int(age1) #Cast here >>> type(age1) <class 'int'>
Password input special method: when entering a password, you need to use the getpass method in the getpass module, that is:
import getpass #Assign user input to pwd variable pwd = getpass.getpass("please enter password:") Please input a password: #Print input print(pwd)
Simple format output: by using the print function, we can achieve simple format output
>>> string = "hello lyshark" >>> print(string) hello lyshark >>> print(string,) # Don't let it wrap >>> print('hello', end = " ") >>> >>> string = "the length of (%s) is %d" %("hello lyshark",len("hello lyshark")) >>> print(string) the length of (hello lyshark) is 13 >>> >>> string = "hello {} --> age {}".format("lyshark",22) >>> print(string) hello lyshark --> age 22 >>> >>> string = "i am %(age).2f" %{"age":22} >>> print(string) i am 22.00
Format conversion output: format output decimal, hexadecimal, octal
>>> import math >>> nHex=0x20 >>> print("Hexadecimal=%x,Decimal system=%d,Octal number system=%o"%(nHex,nHex,nHex)) //Hex = 20, decimal = 32, octal = 40 >>> >>> print("PI=%F"%math.pi) PI=3.141593 >>> print("PI=%10.2f"%math.pi) PI= 3.14 >>> print("PI=%-10.2f"%math.pi) PI=3.14
Detailed usage of format:
>>> print("i am {0}, age {1}, really {0}".format("lyshark",22)) i am lyshark, age 22, really lyshark >>> >>> print("i am {name}, age {age}".format(**{"name":"lyshark","age":"22"})) i am lyshark, age 22 >>> >>> temp = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33]) >>> print(temp) i am 1, age 2, really 3 >>> >>> temp = "i am {:s}, age {:d}, money {:f}".format("lyshark", 18, 8.1) >>> print(temp) i am lyshark, age 18, money 8.100000 >>> >>> temp = "%r %r %r %r" >>> print(temp%(1,2,3,4)) 1 2 3 4 >>> >>> print("Website name:{name},address:{url}".format(name="myblog",url="www.baidu.com")) //Website name: myblog, address: www.baidu.com >>> >>> site={"name":"myblog","url":"www.baidu.com"} >>> print("Website name:{name} address:{url}".format(**site)) //Website name: myblog address: www.baidu.com >>> >>> my_list = ['myblog','www.baidu.com'] >>> print("Website name:{0[0]},address:{0[1]}".format(my_list)) //Website name: myblog, address: www.baidu.com
◆ Python simple operation
Operators are used to perform program code operations. They operate on more than one operand item. In Python, operators can be roughly divided into seven types: arithmetic operators, comparison operators, assignment operators, logical operators, bit operations, etc. the following examples will introduce the use skills of these operators in turn
Arithmetic operators: symbols used to process four operations. Arithmetic symbols are used in all programming languages
>>> num1 = 10 >>> num2 = 20 >>> >>> num1 + num2 30 >>> num1 - num2 -10 >>> num2 % num1 # Modulo: returns the remainder of division 0 >>> num2 // num1 ×× round: returns the integer part of the quotient 2 >>> num1 ** num2 # Power sign: returns num2 power of num1 100000000000000000000
Comparison operator: the result of the comparison operator is a logical value, either true or false
>>> num1 = 10 >>> num2 = 20 >>> >>> num1 == num2 False >>> num1 != num2 True >>> num1 >= num2 False >>> num1 <= num2 True
Assignment operator: the basic assignment operator is = (not equal sign, equal sign is = =), so the operator is often read last
>>> num1 = 10 >>> num2 = 20 >>> >>> num1 = 10 >>> num1 += 10 20 >>> num1 -= 10 10
Bit operation symbol: in a program, bit operation is to directly operate the binary bits of an integer in memory
>>> a=60 # 60 = 0011 1100 >>> b=13 # 13 = 0000 1101 >>> c=0 >>> >>> c= a & b # 12 = 0000 1100 >>> print("a And b: ",c) a And b: 12 >>> >>> c= a | b # 61 = 0011 1101 >>> print("a or b: ",c) a or b: 61 >>> >>> c=a^b # 49 = 0011 0001 >>> print("a XOR b:",c) a XOR b: 49 >>> >>> c=a << 2 # 240 = 1111 0000 >>> print("a Left shift 2",c) a Left shift 2240
Other operators: other operators include common, logical operation, member operation, identity operation, etc
>>> num1 = 10 >>> num2 = 20 >>> num3 = 0 >>> list = [10,20,30,40,50] >>> >>> num1 and num3 0 >>> >>> num1 in list # Determine whether num1 is in the list True >>> num1 not in list False >>> >>> num1 is num3 # Determine whether two identifiers are referenced from one object True >>> num1 is num2 False >>> num1 is not num2 True
Rounding: rounding is used in some special cases
>>> import math >>> >>> math.ceil(3.14) 4 >>> round(3.14) 3
Python data types
The definition of data type in data structure is a set of values and a set of operations defined in this set of values. In Python, data types include numeric types, character type groups, lists, dictionaries, tuples, and other types. The following examples will introduce the use skills of these operators in turn
◆ type of value
Python supports int, float, bool and complex (complex). In Python, there is only one integer type, int, that is, long integer. Like most languages, the assignment and calculation of numeric types are very intuitive. For data exchange between numeric types, please refer to the following list:
int(x) #Convert x to an integer long(x) #Convert x to a long integer float(x) #Convert x to a floating-point number complex() #Create a complex number str(x) #Convert object x to string repr(x) #Convert object x to expression string eval(str) #Used to evaluate a valid Python expression in a string and return an object tuple(x) #Convert sequence s to a tuple list(x) #Convert sequence s to a list chr(x) #Convert an integer to a character unichr(x) #Convert an integer to a Unicode character ord(x) #Convert a character to its integer value hex(x) #Convert an integer to a hexadecimal string oct(x) #Convert an integer to an octal string
Integer to other value: use the conversion command to convert an integer to another value
>>> temp=100 >>> >>> float(temp) 100.0 >>> complex(temp) (100+0j) >>> str(temp) '100'
Integer conversion character: use the conversion command to convert an integer to a character
>>> temp=100 >>> >>> chr(temp) 'd' >>> ord(chr(temp)) 100
Base conversion: use conversion command to implement base conversion
>>> temp=100 >>> >>> hex(temp) '0x64' >>> oct(temp) '0o144'
◆ string type
String is a collection of characters. Python supports string as a data type and provides some rich string processing functions. In the following list are string operation functions supported by python. Next, we will find several common string functions for demonstration
str.capitalize() #Capitalize the first letter of a string str.title() #Capitalize each word in the string str.upper() #Change string to uppercase str.lower() #Make string lowercase str.index() #Find the string corresponding to the index str.find() #Find the string corresponding to the index str.count() #Find out the number of occurrences of elements in a string str.format() #It's also a format str.center() #What characters to fill from both sides of the string str.join() #Connect string with str as separator str.split() #What is the separator to separate strings str.strip() #Remove the spaces on both sides of the string str.replace() #Search and replace str.isupper() #Determine whether it is capitalized str.islower() #Determine whether it is lowercase str.isalnum() #Determine whether it is alphanumeric str.isalpha() #Determine whether it is a letter underline str.isdigit() #Judge whether it is a number str.isspace() #Judge whether it is empty str.startswith() #Find out what character elements start with str.endswith() #Find out what character elements end with
Capitalize: use the capitalize() function to capitalize the initial of a specified string
>>> str="hello lyshark" >>> >>> str.capitalize() 'Hello lyshark'
Capitalize all: use the title() function to capitalize each word in the string
>>> str="hello lyshark" >>> >>> str.title() 'Hello Lyshark'
Find string: use the index() function to find the index number of the specified string. If it doesn't exist, an error will be reported
>>> str="hello lyshark" >>> >>> str.index("hello") 0 >>> str.index("lyshark") 6 >>> str.index("mk") ValueError: substring not found
Find string: use the find() function to find the index number of the specified string. If it does not exist, return - 1
>>> str="hello lyshark" >>> >>> str.find("hello") 0 >>> str.find("lyshark") 6 >>> str.find("mk") -1
Count the number of string Occurrences: count the number of occurrences of the specified string using the count() function
>>> str="hello lyshark" >>> >>> str.count("h") 2 >>> str.count("l") 3 >>> str.count("hello") 1 >>> str.count("mk") 0
String filling: use the center() function to fill the content on both sides of the specified string
>>> str="hello lyshark" >>> >>> str.center(20,'*') '***hello lyshark****' >>> >>> print(str.center(50,'-')) ------------------hello lyshark-------------------
String connection: use the join() function to connect the specified characters in the sequence to generate a new string
>>> str="-" >>> seq=("hello","lyshark","welcome") >>> >>> print(str.join(seq)) hello-lyshark-welcome >>> list =['1','2','3','4','5'] >>> print(''.join(list)) 12345 >>> 'kill %s' % ' '.join(['1024','2234'])
Cut string: use the split() function to divide a string and save it as a list
>>> str="hello-lyshark-welcome" >>> >>> str.split("-") ['hello', 'lyshark', 'welcome']
Remove the spaces on both sides of the string: use the strip() function to remove the spaces on both sides of the specified string
>>> str=" hello lyshark " >>> str ' hello lyshark ' >>> >>> str.strip() 'hello lyshark'
Remove the space on both sides of the string (left / right): use str.lstrip() function to remove the space on the left of the string
>>> str=" hello lyshark " >>> >>> str.rstrip() ' hello lyshark' >>> >>> str.lstrip() 'hello lyshark ' >>>
String find replace: use the replace() function to find and replace the specified string
>>> str="hello lyshark" >>> str 'hello lyshark' >>> >>> str.replace("lyshark","mkdirs") 'hello mkdirs'
Determine whether it is uppercase: use isupper() function to determine whether the specified string is uppercase
>>> str="LYSHARK" >>> str1="lyshark" >>> >>> str.isupper() True >>> str1.isupper() False
Find the beginning and the end: use the startswitch() function to find the character elements that start with a specified letter
>>> str="hello lyshark welcome" >>> >>> str.startswith("hello") True >>> str.startswith("lyshark") False >>> >>> str.startswith("lyshark") or str.endswith("welcome") True >>> str.startswith("lyshark") and str.endswith("welcome") False
◆ type of list
List is the most basic data structure in Python, and it is also the most commonly used one. Each element in the list is assigned a number - its location or index. The first index is 0, the second index is 1, and so on. Next, we will find several common list operation functions for demonstration
list.insert() #Insert an element before specifying the index position in the list list.append() #Insert at end of list list.remove() #Delete the specified element list.pop() #If no index is specified, the last element will pop up, and the returned result is the corresponding element of the pop-up index list.copy() #Shallow copy, only the first layer is copied. If there is a nested sequence, it will not be copied. Copy is required to import the copy module list.extend() #Merging another list is not appending list.index() #Index location of elements in the list list.count() #Count the number of elements in the list list.reverse() #Reverse order list.sort() #Cannot sort numbers and strings together list1 + list2 #Merge two lists and return a new list without modifying the original list list * N #Repeat the list N times to return a new list
Append data to the list: use the append() function to append and write several data to the specified list
>>> list = [1,2,3] >>> list [1, 2, 3] >>> >>> list.append(4) >>> list.append(5) >>> list.append(6) >>> >>> list [1, 2, 3, 4, 5, 6]
Insert data into the list: use the insert() function to insert several data into the specified list to the specified location
>>> list = ["admin","lyshark"] >>> list ['admin', 'lyshark'] >>> >>> list.insert(1,"python") >>> list ['admin', 'python', 'lyshark'] >>> >>> list.insert(2,"ruby") >>> list.insert(2,"ruby") >>> list ['admin', 'python', 'ruby', 'ruby', 'lyshark']
Modify the specified data: modify the field value of the specified element by using the method of name [] variable assignment
>>> list ['admin', 'python', 'ruby', 'ruby', 'lyshark'] >>> list[0]="mkdirs" >>> list ['mkdirs', 'python', 'ruby', 'ruby', 'lyshark'] >>> >>> list[3]="pip" >>> list ['mkdirs', 'python', 'ruby', 'pip', 'lyshark']
Delete the specified data: use the remove() function to delete the specified data, or use the del() function to delete
>>> list ['mkdirs', 'python', 'ruby', 'pip', 'lyshark'] >>> >>> del list[2] #Delete element by subscript >>> list ['mkdirs', 'python', 'pip', 'lyshark'] >>> >>> list.remove("python") #Delete the specified element >>> list ['mkdirs', 'pip', 'lyshark'] >>> >>> list.pop() #Delete the last element of the list 'lyshark' >>> list.pop() 'pip' >>> list ['mkdirs']
Extend a list: use the extend() function to append one list to the next
>>> list1 = ["admin","guest","lyshark"] >>> list2 = [1,2,3] >>> >>> list1.extend(list2) >>> list1 ['admin', 'guest', 'lyshark', 1, 2, 3]
Shallow Copy list: use the copy() function to implement shallow Copy of the list
>>> list1 ['admin', 'guest', 'lyshark', 1, 2, 3] >>> >>> list1_copy = list1.copy() >>> list1_copy ['admin', 'guest', 'lyshark', 1, 2, 3]
Count the number of elements: use count() function to count the number of elements in the list
>>> list = ["admin","admin","lyshark","mkdirs"] >>> >>> list.count("admin") 2 >>> list.count("mkdirs") 1
Forward and reverse sorting: use the sort() reverse() function to sort the specified list elements
>>> list = ["admin","python","ruby","1","3","6","9"] >>> list ['admin', 'python', 'ruby', '1', '3', '6', '9'] >>> >>> list.sort() #Forward sort, element type must be consistent >>> list ['1', '3', '6', '9', 'admin', 'python', 'ruby'] >>> >>> list ['1', '3', '6', '9', 'admin', 'python', 'ruby'] >>> list.reverse() #Reverse sort, element types must be consistent >>> list ['ruby', 'python', 'admin', '9', '6', '3', '1']
Get element subscript: use index() function to get element subscript
>>> list ['ruby', 'python', 'admin', '9', '6', '3', '1'] >>> >>> list.index("admin") 2 >>> list.index("1") 6
Slice of list: use [] to realize various slice operations of list
>>> list=[1,2,3,4,5,6,7,8,9,0] >>> >>> list[1:4] #Remove the elements of subscripts 1-4, excluding 4 [2, 3, 4] >>> >>> list[1:-1] #Remove subscript 1 to - 1, excluding - 1 [2, 3, 4, 5, 6, 7, 8, 9] >>> >>> list[1:] #Take the subscript from 1 to the last data [2, 3, 4, 5, 6, 7, 8, 9, 0] >>> >>> list[:] #Take out all elements [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> >>> list[0::2] #2 spaces at a time when taking elements [1, 3, 5, 7, 9]
Delete data by sharding: use sharding to clear the data in the specified list
>>> list [123, 111, 111, 111, 8, 7, 6, 5, 4, 3, 2, 1] >>> list[0:3] [123, 111, 111] >>> >>> list[0:3]=[] #Replace subscript 0-3 with null, excluding 3 >>> print(list) [111, 8, 7, 6, 5, 4, 3, 2, 1] >>>
Implementation of nested list: two lists are declared at one time and associated with data name
>>> list1,list2 = [[1,"a","b"],[2,"a","b"]] >>> >>> print(list1) [1, 'a', 'b'] >>> print(list2) [2, 'a', 'b']
Find element and modify (1): find the specified element in the list and modify it, only the first time found
[root@localhost]# cat test.py #!/usr/bin/python name = [1,2,3,4,5,1,5,6] if 1 in name: num_of_ele = name.count(1) position_of_ele = name.index(1) name[position_of_ele] = 888 print(name) [root@localhost]# python test.py [888, 2, 3, 4, 5, 1, 5, 6]
Find elements and modify (2): find the specified elements in the list, modify them in batch, and modify all
[root@localhost]# cat test.py #!/usr/bin/python name = [1,2,3,4,5,1,5,6] for i in range(name.count(1)): ele_index = name.index(1) name[ele_index] = 8888888 print(name) [root@localhost]# python test.py [8888888, 2, 3, 4, 5, 8888888, 5, 6]
Type of dictionary
A dictionary is another variable container model, which can store any type of object. A dictionary is a data type that uses key value pairs. Each key value (key = > value) in the dictionary uses a colon as the separator, while the key value pairs and key value pairs are separated by commas. The whole dictionary is included in curly braces, and the dictionary has two features. The first feature is that the data in the dictionary is disorderly stored, and the second feature is that The key in the sex dictionary must be unique, so the key is naturally de duplicated. The following are the format declarations of the dictionary:
person = {"name": "lyshark", "age": 22} person = dict({"name": "lyshark", "age": 22}) info = { 'stu1': "Taka Kato", 'stu2': "Yui Hatano", 'stu3': "Xiao zemaria", }
Dictionaries need to use dictionary specific operation functions. The common functions of dictionaries are as follows. I will use different examples to illustrate later
dict.get(key) #Get the value of a key dict.has_key(key) #Judge whether the dictionary has this key. It has been abolished in Python 3. Use in to judge dict.keys() #Return all key s as a list dict.values() #Return all value s as a list dict.items() #The key value of the dictionary is divided into tuples, and all tuples form a list dict.pop(key) #Pop up a key value dict.popitem() #Pop key value randomly dict.clear() #Clear all elements in dictionary dict.copy() #Dictionary copy, d2=d1.copy() is shallow copy, if deep copy needs copy module dict.fromkeys(s) #Generate a new dictionary dict.update(key) #Merge a dictionary into the current dictionary dict.iteritems() #To generate a key value iterator, you can use next() to take down a key value dict.iterkeys() #Generate key iterator dict.itervalues() #Generate values iterator
Add Dictionary: on the basis of info dictionary, add a field info["stu4"] = "Cang teacher"
>>> info {'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria'} >>> info["stu4"] = "Aoi Sora" >>> >>> info {'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria', 'stu4': 'Aoi Sora'}
Modify Dictionary: on the basis of info dictionary, modify stu1: Kato hawk to stu1: golden finger
>>> info {'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria', 'stu4': 'Aoi Sora'} >>> >>> info["stu1"] = "Golden finger" >>> info {'stu1': 'Golden finger', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria', 'stu4': 'Aoi Sora'}
Delete Dictionary: on the basis of info dictionary, delete several dictionaries. The following provides a variety of deletion methods
>>> info {'stu1': 'Golden finger', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria', 'stu4': 'Aoi Sora'} >>> >>> info.pop("stu1") #Delete by pop function 'Golden finger' >>> info {'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria', 'stu4': 'Aoi Sora'} >>> >>> del info["stu4"] #Delete by del command >>> info {'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria'} >>> >>> info.popitem() #Randomly delete elements ('stu3', 'Xiao zemaria')
Search Dictionary: on the basis of info dictionary, several query tasks are completed, and several methods are provided here
>>> info {'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria'} >>> >>> "stu1" in info #Standard query method True >>> >>> info.get("stu1") #Use get function to query 'Taka Kato' >>> >>> info["stu2"] 'Yui Hatano'
Update Dictionary: on the basis of info dictionary, update the contents of dictionary, and merge temp dictionary and info dictionary
>>> info {'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria'} >>> >>> temp = {1:2,"stu4":"Aoi Sora"} >>> >>> info.update(temp) >>> info {'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria', 1: 2, 'stu4': 'Aoi Sora'}
Traversal Dictionary: there are two kinds of dictionary traversal methods. The second one is recommended because it is the fastest
>>>Info = {'stu1': 'Kato Hawk','stu2 ':' potono's lichen ','stu3': 'little zemaria'} >>> >>> for keys,values in info.items(): ... print(keys,values) ... stu1 Kato Hawk stu2 potono stu3 little zemaria >>> for keys in info: ... print(keys,info[keys]) ... stu1 Kato Hawk stu2 potono stu3 little zemaria
Index Dictionary: the dictionary also supports the way of index to obtain the elements in the dictionary, only the key must be used as the index
>>> info = {'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria'} >>> >>> info['stu2'] 'Yui Hatano' >>> >>> len(info) 3 >>> >>> dict = {"Full name":"Taka Kato","Score":[98,99,87]} >>> >>> dict["Full name"] 'Taka Kato' >>> dict["Score"] [98, 99, 87] >>> dict["Score"][2:] [87]
Dictionary unpacking: decomposes a dictionary into independent tuples and assigns tuples to other variables
>>> dict = {"Full name":"Taka Kato","Score":[98,99,87]} >>> t1,t2 = dict.items() >>> >>> print(t1) ('Full name', 'Taka Kato') >>> print(t2) ('Score', [98, 99, 87]) >>> >>> k1,k2 = {"x":100,"y":200} >>> print(k1) x
Merge list into Dictionary: combine two lists into a dictionary, where list1 is key and List2 is values
>>> dict = {} >>> list = [100,200,300,400,500] >>> head = ["MemTotal","MemFree","Cached","SwapTotal","SwapFree"] >>> >>> for (keys,values) in zip(head,list): ... dict[keys] = values ... >>> dict {'MemTotal': 100, 'MemFree': 200, 'Cached': 300, 'SwapTotal': 400, 'SwapFree': 500} >>> >>> dict(map(lambda x,y:[x,y],head,list)) {'MemTotal': 100, 'MemFree': 200, 'Cached': 300, 'SwapTotal': 400, 'SwapFree': 500} >>> >>> dict(zip(head,list)) {'MemTotal': 100, 'MemFree': 200, 'Cached': 300, 'SwapTotal': 400, 'SwapFree': 500}
Dictionary key value adjustment: the key in the dictionary and the value in the dictionary are adjusted
>>> {key:value for key,value in zip(head,list)} {'MemTotal': 100, 'MemFree': 200, 'Cached': 300, 'SwapTotal': 400, 'SwapFree': 500} >>> {value:key for key,value in zip(head,list)} {100: 'MemTotal', 200: 'MemFree', 300: 'Cached', 400: 'SwapTotal', 500: 'SwapFree'}
Dictionary split into lists: split a complete dictionary into two lists
>>> dict = {'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria'} >>> keys= dict.keys() >>> values = dict.values() >>> >>> print("keys:{}".format(keys)) keys:dict_keys(['stu1', 'stu2', 'stu3']) >>> >>> dict = {'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria'} >>> >>> keys,values = zip(*dict.items()) >>> print("Keys:",str(keys)) Keys: ('stu1', 'stu2', 'stu3') >>> dict = {'stu1': 'Taka Kato', 'stu2': 'Yui Hatano', 'stu3': 'Xiao zemaria'} >>> >>> keys = [] >>> values = [] >>> items = dict.items() >>> for x in items: ... keys.append(x[0]),values.append(x[1]) ... >>> print(str(keys)) ['stu1', 'stu2', 'stu3']
Dictionary merge and copy: merges dictionaries, but overwrites the original key value when there is the same key
>>> dict1 = {"x":1,"y":2} >>> dict2 = {"a":3,"b":4} >>> dict3 = {} >>> >>> dict3 = {**dict1,**dict2} >>> print(dict3) {'x': 1, 'y': 2, 'a': 3, 'b': 4} >>> >>> dict3.update(dict1) >>> dict3.update(dict2) >>> print(dict3) {'x': 1, 'y': 2, 'a': 3, 'b': 4} >>> >>> import copy >>> n1 = {"k1": "wu", "k2": 123, "k3": ["lyshark", 456]} >>> n2 = {} >>> >>> n2 = copy.deepcopy(n1) >>> print(n2) {'k1': 'wu', 'k2': 123, 'k3': ['lyshark', 456]}
Complex table data storage:
>>> dict1 = {"name":"admin","age":19,"salary":3000,"address":"beijing"} >>> dict2 = {"name":"guest","age":20,"salary":4000,"address":"shanghai"} >>> dict3 = {"name":"lyshark","age":21,"salary":5000,"address":"shenzhen"} >>> table = [dict1,dict2,dict3] # Used to get the specified field data of the specified person >>> print(table[1].get("name")) guest >>> print(table[2].get("address")) shenzhen # Print everyone's name in the form >>> for i in range(len(table)): ... print(table[i].get("name")) ... admin guest lyshark
◆ tuple type
Tuple is a common data structure in Python. Tuple is composed of different elements. Each element can store different types of data, such as string, number or even tuple. Tuple is write protected, that is, after tuple is created, no modification can be done. Tuple usually represents a row of data, while elements in tuple represent different data items. Once tuple is created, it cannot be modified It is also called read-only list. Tuples use parentheses. Lists use square brackets. Tuples are easy to create. You only need to add elements in brackets and separate them with commas
Create tuples: see how tuples are created in the same instance
>>> tup1 = ("google","baidu",1997,1998) >>> tup2 = (1,2,3,4,5,6,7) >>> tup3 = "a","b","c","d" >>> >>> tup1 ('google', 'baidu', 1997, 1998) >>> tup2 (1, 2, 3, 4, 5, 6, 7) >>> tup3 ('a', 'b', 'c', 'd') >>> >>> type(tup1) <class 'tuple'>
Access tuple: a tuple can use a subscript index to access the value in the tuple
>>> tup1 ('google', 'baidu', 1997, 1998) >>> >>> print("tup1[0:]",tup1[0]) tup1[0:] google >>> print("tup1[1:2]",tup1[1:2]) tup1[1:2] ('baidu',)
Join tuple: element value in tuple is not allowed to be modified, but we can join tuple
>>> tup1 = (1,2,3,4) >>> tup2 = ("abc","xyz") >>> >>> tup3 = tup1+tup2 >>> print(tup3) (1, 2, 3, 4, 'abc', 'xyz')
Delete tuple: the element value in tuple is not allowed to be deleted, but we can use del statement to delete the whole tuple
>>> tup = ("admin","lyshark", 1997, 2000) >>> >>> print(tup) ('admin', 'lyshark', 1997, 2000) >>> del tup; >>> print(tup)
List to tuple: converts a list to a primitive
>>> list = ["admin","lyshark","guest"] >>> >>> tuple = tuple(list) >>> >>> tuple ('admin', 'lyshark', 'guest')
Data statistics: count () function is used to count other data in tuple
>>> tuple ('admin', 'lyshark', 'guest') >>> >>> tuple.count("lyshark") #Count the occurrence of lyshark 1 >>> tuple.index("lyshark") #Count the index location of lyshark 1
Element modification (extension): in the absence of nesting, tuples are immutable objects, but lists within tuples are mutable
>>> tup=("lyshark",[1,2,3,4,5]) >>> tup ('lyshark', [1, 2, 3, 4, 5]) >>> >>> tup[1].pop() 5 >>> tup ('lyshark', [1, 2, 3, 4])
Tuple unpacking (expanding): separate two tuples and queries, and store them in two variables respectively
>>> tup1,tup2=((1,2,3),("a","b","c")) >>> print(tup1) (1, 2, 3) >>> >>> print(tup2) ('a', 'b', 'c')
◆ type of collection
A set is an unordered and unrepeatable data combination. A set is naturally de duplicated. When a list is turned into a set, it is automatically de duplicated. A set does not support index, element acquisition, and slicing. There is no specific syntax format. You can only create a set through a factory function, but directly create a string. The elements in a set set must be iterative objects, and all elements will not be duplicated, unlike a list list It can be repeated
set.add(item) #Add an item to the set. If the item is already in the set, it has no effect set.remove(item) #Delete item from set. If item is not a member of set, KeyError exception will be thrown set.discard(item) #Delete item from set. If item is not a member of set, it has no effect set.pop() #Randomly delete a set element and delete it from the set. If a variable is received, the deleted element will be received set.clear() #Delete all elements in set set.copy() #Shallow copy set.update(t) #Add all elements in t to set, t can be another set, a sequence set.union(t) #Union, return all elements in set and t set.intersection(t) #Find intersection, return all elements in both set and t set.intersection_update(t) #Calculate the intersection of set and t, and put the result in set set.difference(t) #Subtraction set, return all elements in set but not in t set.difference_update(t) #Remove all elements from the set that are also in t set.symmetric_difference(t) #Find the symmetric difference set, and return the set composed of all elements in the set without T and elements in the set without t set.sysmmetric_difference_update(t) #Calculate the symmetric difference set between set and t, and put the result into set set.isdisjoint(t) #Returns True if set and t do not have the same entry set.issubset(t) #Returns True if s is a subset of t set.issuperset(t) #Returns True if s is a superset of t
Create a collection: create a collection element in two ways
>>> s = {"tom","cat","name","lyshark"} >>> s = set({"tom","cat","name","lyshark"}) >>> >>> s {'tom', 'cat', 'name', 'lyshark'} >>> type(s) <class 'set'>
Define variable set: define a variable set. The elements in the set are different
>>> set_test = set("hello") >>> set_test {'o', 'e', 'l', 'h'}
Define immutable set: define an immutable set. The elements in the set are different
>>> set_test = set("hello") >>> set_test {'o', 'e', 'l', 'h'} >>> >>> no_set_test = frozenset(set_test) >>> no_set_test frozenset({'o', 'e', 'l', 'h'})
Subsets: subsets are part of a set, so they are also called partial sets
>>> A = set('abcd') >>> B = set("cdef") >>> C = set("ab") >>> >>> C<A #C is A subset of A True >>> C.issubset(A) #C is A subset of A True >>> C<B #C is not a subset of B False
Union: the union of a set is a set of all the elements of the set, excluding other elements
>>> A {'d', 'a', 'c', 'b'} >>> B {'f', 'd', 'e', 'c'} >>> >>> A | B {'f', 'b', 'c', 'a', 'e', 'd'} >>> A.union(B) {'f', 'b', 'c', 'a', 'e', 'd'}
Intersection: the intersection of two sets A and B is A set that contains all elements that belong to both A and B, but no other elements
>>> A {'d', 'a', 'c', 'b'} >>> B {'f', 'd', 'e', 'c'} >>> >>> A & B {'c', 'd'} >>> A.intersection(B) {'c', 'd'}
Difference set: the difference set of A and B is A set of all elements belonging to A and not belonging to B
>>> A {'d', 'a', 'c', 'b'} >>> B {'f', 'd', 'e', 'c'} >>> >>> A - B {'a', 'b'} >>> A.difference(B) {'a', 'b'}
Symmetry difference: the symmetry difference of two sets is a set composed of elements that belong to only one set but not the other
>>> A {'d', 'a', 'c', 'b'} >>> B {'f', 'd', 'e', 'c'} >>> >>> A ^ B {'f', 'b', 'a', 'e'} >>> A.symmetric_difference(B) {'f', 'b', 'a', 'e'}
Add element: use the add() function to add an element to an existing collection
>>> s = {1,2,3,4,5,6} >>> s {1, 2, 3, 4, 5, 6} >>> s.add("s") >>> s.add("e") >>> s.add("t") >>> >>> s {1, 2, 3, 4, 5, 6, 't', 's', 'e'}
Empty set: use the clear() function to empty all elements in a set
>>> s {1, 2, 3, 4, 5, 6, 't', 's', 'e'} >>> >>> s.clear() >>> >>> s set()
Delete the specified element: use the remove,discard function to delete the specified element in the collection
>>> s = {1,2,3,4,5} >>> s {1, 2, 3, 4, 5} >>> >>> s.remove(3) >>> s {1, 2, 4, 5}
Batch update element: use the update() function to update this collection with its own union with another
>>> s ={"p","y"} >>> s {'p', 'y'} >>> >>> s.update(["H","e"],{"1","2","3"}) >>> s {'H', '1', 'y', 'p', '2', 'e', '3'}
Expand knowledge (1): find differences in multiple data
# Database has old_dict = { "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 }, "#2":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 }, "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 } } # Data newly reported by cmdb new_dict = { "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 800 }, "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 }, "#4":{ 'hostname':'c2', 'cpu_count': 2, 'mem_capicity': 80 } } old_set=set(old_dict) new_set=set(new_dict) del_set=old_set.difference(new_set) add_set=new_set.difference(old_set) flush_set=old_set.intersection(new_set) for i in del_set: old_dict.pop(i) for i in add_set: old_dict[i]=new_dict[i] for i in flush_set: old_dict[i] = new_dict[i] print(old_dict)
Expand knowledge (2): find differences in multiple data
# Database has old_dict = { "#1":8, "#2":4, "#3":2, } # Data newly reported by cmdb new_dict = { "#1":4, "#3":4, "#4":2, } old_set = set(old_dict.keys()) print(old_set) new_set = set(new_dict.keys()) print(new_set) remove_set = old_set.difference(new_set) print(remove_set) add_set = new_set.difference(old_set) print(add_set) update_set = old_set.intersection(new_set) print(update_set)
◆ sequence supplement
Sequence type refers to an ordered set of objects indexed to nonnegative integers, including strings, lists, tuples, strings that are character based, lists and tuples that are sequences of any python object, characters and tuples that are immutable, and lists that support inserting, deleting, and replacing elements. All sequences support iteration, of course tuples are immutable objects, and element operations are not supported, Of course, there are nested list dictionaries that can be operated. Here are some common sequence operation functions:
s + r #Connection string, with data s * n #n replicates of s v1,v2...vn = s #Variable unpack s[i] #Indexes s[i:j] #Section s[i:j:stride] #Extended slice x in s,x not in s #Member relationship for x in s: #iteration all(s) #Returns True if all items in s are True any(s) #Returns True if any item in s is True len(s) #Length, number of elements min(s) #The smallest term in s max(s) #The largest term in s sum(s [,initial]) #Sum of items with optional initializers
All judgment: returns True if all items in temp are True
>>> temp = [1,1,1,1,1,1] >>> temp1 = [1,1,1,1,0,1] >>> >>> all(temp) True >>> all(temp1) False
Any judgment: returns True if any item in temp is True
>>> temp = [1,1,1,1,1,1] >>> temp1 = [1,1,1,1,0,1] >>> >>> any(temp) True >>> any(temp1) True
len count elements: count related elements such as lists or dictionaries
>>> temp = [1,1,1,1,1,1] >>> len(temp) 6
min returns min: returns the smallest value in the list
>>> temp = [1,2,3,4,5,6,7,8,9] >>> >>> min(temp) 1
max return maximum: returns the maximum value in the list
>>> temp = [1,2,3,4,5,6,7,8,9] >>> >>> max(temp) 9
◆ operation of documents
Open: the open function is used to open a file and return a handle
>>> f=open("./test.txt","r") >>>
popen: use popen to store command execution results and print them
>>> temp=os.popen("ifconfig").readlines() >>> temp ['eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500\n']
read: this function reads all the contents of the file at once
>>> f=open("./test.txt","r") >>> f.read()
readline: this function reads one row of data at a time until all are read
>>> f=open("./test.txt","r") >>> f.readline() 'root:x:0:0:root:/root:/bin/bash\n' >>> f.readline() 'bin:x:1:1:bin:/bin:/sbin/nologin\n' >>> f.readline() 'daemon:x:2:2:daemon:/sbin:/sbin/nologin\n'
Readlines: use readlines to read all content at once, which is equivalent to loading all
>>> f=open("./test.txt","r") >>> f.readlines()
Seek: use seek to move the cursor position, and tell to get the current cursor position
>>> f=open("./test.txt","r") >>> f.tell() #Query the current cursor position 0 >>> f.readline() #After reading a row 'root:x:0:0:root:/root:/bin/bash\n' >>> >>> f.tell() #Query the cursor position again 32 >>> >>> f.read() #After full reading, the cursor is at the back of the file 'bin:x:1:1:bin:/bin:/sbin/nologin\ndaemon:x:2:2:daemon:/sbin:/sbin/nologin\n' >>> >>> f.seek(32) #Move cursor to 32 >>> >>> f.read() #Reread data 'bin:x:1:1:bin:/bin:/sbin/nologin\ndaemon:x:2:2:daemon:/sbin:/sbin/nologin\n'
flush: forces the data in memory to be flushed and written to disk
>>> import sys >>> import time >>> >>> for i in range(40): ... sys.stdout.write("#") ... sys.stdout.flush() #Force data in memory to be written to hard disk ... time.sleep(0.1)
Close: use close to close the file handle. Remember to close every time the open file is used up
>>> f=open("./test.txt","r") >>> f.readlines() >>> f.close()
Next: read one row of data at a time, and use the next function to load the next row
>>> f = open("./test.txt", "r") >>> print ("File name is: ", f.name) >>> for index in range(5): ... line = next(f) ... print ("The first %d That's ok - %s" % (index,line)) >>> f.close()
truncate: intercepts data. You can specify the number of bytes to be intercepted each time
>>> f = open("./test.txt", "r+") >>> print ("File name is: ", f.name) >>> f.truncate(10) #Intercept 10 bytes >>> str = f.read() >>> print ("Read data: %s" % (str)) >>> f.close()
with: automatically open the file and release the file handle after execution
>>> with open('test.txt') as f: ... print(f.read())
Linecache: open a file by using the linecache module, and calculate the total number of files
import sys import linecache count = len(open("./ip.log","r").readlines()) print("File rows(Including spaces): %d" %count) count = linecache.getlines("./ip.log") print("File rows(Support for large files): %d" %len(count))
Python process control
◆ while cycle
Branch structure:
# -*- coding: utf-8 -*- import sys number = 38 user_input = int(input("Enter a number:")) if user_input == number: print("Bingo!") elif user_input < number: print("Guess it's small.!") else: print("Guess big.!")
To implement the addition cycle:
import sys count = 1 sum = 0 while count <=100: sum+=count count+=1 print(sum)
Interrupt loop: demonstrates when a while loop is interrupted
import os count = 0 while count <=9: print(count, end=' ') if count == 5: break count += 1 else: print('end')
Print string: print the specified string, print every element in it, and decrease every time
import sys string = "hello lyshark" while string: print(string) string = string[:-1] else: print("gae over")
List printing: display all the elements in the specified list one by one. Here are three methods
>>> list=[1,2,3,4,5,6] >>> count =0 >>> >>> while list: ... print(list[0]) ... list.pop(0) ... >>> list=[1,2,3,4,5,6] >>> while list: ... print(list[-1]) ... list.pop() ... >>> list=[1,2,3,4,5,6] >>> while count < len(list): ... print(list[count]) ... count+=1
Exercise example: find the sum of all even numbers within 100, and use nested judgment
>>> num=0 >>> sum=0 >>> while num <=100: ... if num %2 ==0: ... sum=sum+num ... else: ... pass ... num=num+1
Exercise example: display all keys of the specified dictionary one by one, and state the total number of keys after the display
>>> d1 = {'x':1,'y':23,'z':78} >>> keylists = d1.keys() >>> while keylists: print(keylists[0]) keylists.pop[0] else: print(len(d1))
Exercise example: create a list of all odd numbers within 100
>>> l1 = [] >>> x = 1 >>> while x < 100: l1.append(x) x += 2
Practice example: there are two lists L1 and L2 as follows. Take the element in the first list as the key and the element in the second list as the value to generate a new dictionary d1
>>> l1 = [0,1,2,3,4,5,6] >>> l2 = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] >>> d1 = {} >>> count = 0 >>> if len(l1) == len(l2): while count < len(l1): d1[l1[count]] = l2[count] count += 1 >>> print(d1)
Exercise example: loop and print the relevant text, and exit when it reaches 100 times
count = 0 while True: print("hello lyshark:",count) count +=1 if count == 100: print("break") break
Practice example: simulate the login applet. The password is required for program startup, and judge whether the login is successful if the number is less than 3 times. Otherwise, login is forbidden
import getpass import os name = "lyshark" pwd = "123123" count = 0 while True: if count < 3: print("Please enter user name and password:") username = input("User name:") password = getpass.getpass("Password:") if username == name and password == pwd: print("Congratulations on your landing!") break else: print("Login failed! Wrong user name or password") else: print("You've lost three times,Exit....") break count += 1
◆ for circulation
List traversal: print elements in a list by using the for loop
import os names = ["tom","admin","lyshark","jack"] for x in names: print(x)
List iteration: for a sequence, it can also be iterated by index
import os names = ["tom","admin","lyshark","jack"] for x in range(len(names)): print(names[x])
Print sequence: through for loop, traverse and print a sequence
import os T = [(1,2),(3,4),(5,6),(7,8)] for (a,b) in T: print(a,b)
Loop traversal: traverses all numbers in the range of 0-9, and prints out the odd numbers through the loop control statement
import os for i in range(10): if i % 2 == 0: continue print(i, end=' ')
Loop traversal: print the first three elements of a list through loop control statements
import os names = ['Tom', 'Peter', 'Jerry', 'Jack', 'Lilly'] for i in range(len(names)): if i >= 3: break print(names[i])
Loop traversal: print 99 multiplication table through for loop
import os for j in range(1, 10): for i in range(1, j+1): print('%d*%d=%d' % (i, j, i*j), end='\t') i += 1 print() j += 1
Loop traversal: through the range function, we can also achieve traversal
>>> string="hello world my name lyshark" >>> for i in range(0,len(string),2): ... print(string[i]) >>> list=[1,2,3,4,5] >>> for i in range(len(list)): ... list[i]+=1 >>> list [2, 3, 4, 5, 6] >>> for i in range(1,10,2): print(i)
enumrate: add a sequence number to an iterative object. By default, the number starts from 0. You can set it to start from 1
>>> list=["Sora Aoi","Xiao zemaria","Yoshizawa Akiho"] >>> for (x,y) in enumerate(list,1): print(x,y) 1 Sora Aoi 2 Xiao zemaria 3 Yoshizawa Akiho
zip() function: the zip function is often used to construct a dynamic dictionary
>>> L1 = [1,2,3,4,5] >>> L2 = ['a','b','c','d','e',] >>> zip(L1,L2) >>> >>> keys = [1,2,3,4,5,6,7] >>> vaules = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] >>> D = {} >>> for (k,v) in zip(keys,values) D[k] = v >>> D
◆ other examples
Exercise example: display all elements in the specified dictionary d1 separately, that is, dictionary traversal printing
>>> d1 = {'x':123,'y':321,'z':734} >>> for (k,v) in d1.items(): print(k,v) y 321 x 123 z 734
Exercise example: display the odd index elements of l1 in the list one by one
>>> l1=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] >>> >>> for i in range(1,len(l1),2): print(l1[i])
Exercise example: define all elements belonging to list l1 but not belonging to list l2 as a new list l3 and add them to it
>>> l1=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] >>> l2=['Sun','Mon','Tue','Thu','Sat'] >>> l3 = [] >>> for i in l1: >>> if i not in l2: >>> l3.append(i)
Exercise example: please remove each element belonging to the removelist list from the namelist (it belongs to removelist, but not to the neglect of namelist)
>>> namelist=['stu1','stu2','stu3','stu4','stu5','stu6','stu7'] >>> removelist=['stu3','stu7','stu9'] >>> for i in removelist: >>> if i in namelist: >>> namelist.remove(i) >>> print(namelist)
Practice example: there are four numbers: 1, 2, 3, and 4. How many different and unrepeated three digit numbers can be composed? How many are each?
Program analysis: the numbers that can be filled in hundreds, tens and ones are all 1, 2, 3 and 4. After all the permutations are formed, the unqualified permutations are removed
>>> for i in range(1,5): ... for j in range(1,5): ... for k in range(1,5): ... if(i!=k) and (i!=j) and(j!=k): ... print(i,j,k) ...
Practice example: input a certain day of a certain year, and the program automatically judges the day as the day of the year?
Program analysis: take October 1 as an example, we should first add up the first nine months, and then add one day, which is the day of the year. In special cases, when the leap year and the input month is greater than 2, we need to consider adding one more day
# -*- coding: UTF-8 -*- year = int(input('year:\n')) month = int(input('month:\n')) day = int(input('day:\n')) months = (0,31,59,90,120,151,181,212,243,273,304,334) if 0 < month <= 12: sum = months[month - 1] else: print ('data error') sum += day leap = 0 if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)): leap = 1 if (leap == 1) and (month > 2): sum += 1 print ('it is the %dth day.' % sum)
Exercise example: output 9 * 9 multiplication formula table, consider lines and columns, 9 lines and 9 columns in total, i control line, j control column
import os import sys for x in range(1,10): print() for y in range(1,x+1): print("%d*%d=%d "%(y,x,x*y),end="")
Example: write a string traversal search tool, the code is as follows
import os import sys ls="Type help() for interactive help, or help(object) for help about object" find="help" for x in range(len(ls)): temp=len(find) if str(ls[x:x+temp]) == str(find): print(ls[x:x+temp],x) break
Exercise example: by using the sleep function in the time module, let the program execute a loop every 1 second
import os import time dic={1:"admin",2:"guest"} for key,value in dict.items(dic): print(key,value) time.sleep(1)
Example: input a line of characters and count the number of English letters, spaces, numbers and other characters
import os import string strs=input("Please enter a string:") letters=0 space=0 digit=0 others=0 for x in range(len(strs)): ch=strs[x] if ch.isalpha(): letters+=1 elif ch.isspace(): space+=1 elif ch.isdigit(): digit+=1 else: others+=1 print("char=%d,space=%d,digit=%d,others=%d"%(letters,space,digit,others))
Exercise example: read the db configuration file, and judge whether login is allowed according to the account password in the file
import os import sys def login(x,y): fp=open("db","r",encoding="utf-8") data=fp.readline().split(":") count=len(open("db","r").readlines()) username=data[0] password=data[1] for i in range(3): if x==username.strip() and y==password.strip(): print("Landing successfully") break else: data=fp.readline().split(":") username=data[0] password=data[1] continue fp.close() login("admin","admin") login("lyshark","lyshark")
Implementation element classification: there is the following value set list, which saves all values greater than 66 to the first key of the dictionary, and saves values less than 66 to the values of the second key, namely {'k1': all values greater than 66, 'k2': all values less than 66}
list= [11,22,33,44,55,66,77,88,99] bignum=[] smallnum=[] dir={} for num in list: if num>66: bignum.append(num) if num<66: smallnum.append(num) else: pass dir['k1']=bignum dir['k2']=smallnum print(dir)
Implement element lookup: find elements, move spaces, and find all elements that start with a or a and end with c
li = ["alec", " aric", "Alex", "Tony", "rain"] tu = ("alec", " aric", "Alex", "Tony", "rain") dic = {'k1': "alex", 'k2': ' aric', "k3": "Alex", "k4": "Tony"} for i in li: if i.strip().capitalize().startswith('A') and i.strip().endswith('c'): print(i) for i in tu: if i.strip().capitalize().startswith('A') and i.strip().endswith('c'): print(i) for i in dic.values(): if i.strip().capitalize().startswith('A') and i.strip().endswith('c'): print (i)
Realize commodity output: output commodity list, user input serial number, display commodity selected by user
#Method 1 l1=[1,2,3,4] l2=["Mobile phone", "Computer", 'Mouse pad', 'Yacht'] d=dict(zip(l1,l2)) print(d) num=input("Please enter the product number:") print("The product you selected is %s" %d[int(num)]) #Method two li = ["Mobile phone", "Computer", 'Mouse pad', 'Yacht'] for k, i in enumerate(li): print(k,i) k=input("Please enter the product number:") print("The product you selected is %s" % li[int(k)])
Guessing game: it allows users to guess the age continuously, but only gives 3 chances at most, and quit the program if the guessing is wrong
# -*- coding:utf-8 -*- age = 22 count = 0 for i in range(10): if count < 3: a = int(input("Please enter a guess:")) if a == age: print("Congratulations,Bingo") break elif a > age: print("You've got a big number") else: print("Your guess is small") else: b = input("That's not right,Do you keep playing?(yes or not):") if b == 'yes': count = 0 continue else: print("Bye!Play again next time.") count += 1
Realize three - level menu: realize user interaction, display the three - level linkage selection of province, city and county
dic = { "Hebei": { "Shijiazhuang": ["Luquan", "Gaocheng", "Yuanshi"], "Handan": ["throughout the year", "Shexian County", "Cixian"], }, "Hunan": { "Changsha":['a','b','c'], "Zhuzhou":['d','e','f'] }, "Hubei": { "Wuhan":['g','h','i'], "Huangshi":['j','k','l'] } } for k in dic.keys(): print(k) flag=True while flag: n=input("Please enter your province:") for k in dic.keys(): if n in dic.keys(): if k == n: for i in dic[n].keys(): print(i) w = input("Please enter your city:") for i in dic[n].keys(): if w in dic[n].keys(): if i == w: for k in dic[n][w]: print(k) s=input("Please enter your county:") for j in dic[n][w]: if s in dic[n][w]: if j==s: print("Your location is:%s province%s city%s county" % (n,w,s)) flag = False break else: print('No, please re-enter') break else: print('No, please re-enter') break else: print('No, please re-enter') break
Implement a shopping cart: implement a shopping cart applet, and meet the following requirements
product = [ ("iphone",5800), ("watch",380), ("bike",800), ("book",120), ("computer",4000) ] shopping_car = [] salary = input("Please input your money: ") if salary.isdigit(): salary = int(salary) while True: for i in enumerate(product): print(i) user_choice = input(">>>perhaps q:") if user_choice.isdigit(): user_choice = int(user_choice) if user_choice >= 0 and user_choice < len(product): p_item = product[user_choice] if salary >= p_item[1]: shopping_car.append(p_item[0]) salary -= p_item[1] print("You bought it.\033[32m%s\033[0m,Your balance is surplus\033[31m%s\033[0m" % (p_item[0], salary)) else: print("\033[31m Your balance is insufficient\033[0m") else: print("Items you entered[%s]Non-existent,Please re-enter" % user_choice) elif user_choice == 'q': print("You bought these goods:".center(30,"-")) for i in shopping_car: print("\033[32m%s\033[0m" %i) print("\033[31m balance%s\033[0m" %salary) exit() else: print("What you entered[%s]Non-existent" % user_choice) else: print("The amount you entered is incorrect! Please re-enter the amount!")
Python advanced features
◆ Python iterator
Iterators are a way to access collection elements. Iterator objects are accessed from the first element of the collection until all elements are accessed. Iterators can only move forward and not backward. Iterators are especially suitable for traversing some huge or infinite collections, such as files with a size of GB level, which is particularly efficient
Create a basic iterator: first declare a list, then use 'iterator' to turn it into an iterator, and iterate over the iterated object through 'next'
>>> list = [1,2,3,4,5,6,7,8,9,10] >>> >>> item = list.__iter__() >>> type(item) <class 'list_iterator'> >>> >>> item.__next__() 1 >>> item.__next__() 2 >>> next(item) 3 >>> next(item) 4
Iterator and tuple conversion: by using the enumerate method, the list is converted to an iterator and then forced to a tuple
>>> listvar = ["Lu Dong Bin", "Zhang Guo Lao", "LAN Tsai", "Special obedient", "Letinous edodes", "Han Zhong Li", "Wang Wen"] >>> >>> iter = enumerate(listvar) # Convert to iterator >>> dict = tuple(iter) # Convert to tuple >>> print(dict) ((0, 'Lu Dong Bin'), (1, 'Zhang Guo Lao'), (2, 'LAN Tsai'), (3, 'Special obedient'), (4, 'Letinous edodes'), (5, 'Han Zhong Li'), (6, 'Wang Wen'))
Loop traversal iteration element: because the iterator will report an error at the end of traversal, the try statement is used to throw an exception
>>> listvar = ["Lu Dong Bin", "Zhang Guo Lao", "LAN Tsai", "Special obedient", "Letinous edodes", "Han Zhong Li", "Wang Wen"] >>> item = listvar.__iter__() >>> >>> while True: ... try: ... temp = next(item) ... print(temp) ... except StopIteration: ... break
◆ Python generator
Generator is a special program, which can be used to control the iterative behavior of loops. In Python, generator is a kind of iterator. Using yield return value function, yield will pause every time you call it, and next() function and send() function can be used to restore the generator
When we call a generator function, we actually return an iterator object
In Python, as long as the expression is used, yield function is usually called generator
When you run the generator, each time you encounter a yield function, it automatically saves and pauses execution until you use the next() method to continue the iteration
Unlike ordinary functions, a generator is a function that returns an iterator, which can only be used for iterative operations. More simply, understand that a generator is an iterator
Before learning the generator, we need some pre knowledge. First, we need to study list parsing. List parsing is an application of Python iteration mechanism. It is often used to create new lists. Therefore, to be placed in [], list parsing is very flexible. Users can quickly create a set of list elements of corresponding rules and support iterative operation
Factoring: realize the iterative factoring of list through list analytic expression
>>> temp1 = [1,2,3,4,5] >>> temp2 = [ x ** 2 for x in temp1 ] >>> temp1 [1, 2, 3, 4, 5] >>> temp2 [1, 4, 9, 16, 25]
Factoring: through list parsing, iterative factoring is realized, and only data larger than 2 (if x > = 2) is printed
>>> temp1 = [1,2,3,4,5] >>> temp2 = [ x**2 for x in temp if x>=2 ] >>> temp1 [1, 2, 3, 4, 5] >>> temp2 [4, 9, 16, 25]
Factorization: through the list analytical formula, the iterative factorization is realized, and the relevant data is generated through the range function
>>> temp = [ (x**2)/2 for x in range(1,10)] >>> temp [0.5, 2.0, 4.5, 8.0, 12.5, 18.0, 24.5, 32.0, 40.5]
Data merging: through list parsing, the two lists are merged according to rules
>>> temp1=["x","y","z"] >>> temp2=[1,2,3] >>> temp3=[ (i,j) for i in temp1 for j in temp2 ] >>> temp3 [('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]
File filtering: through the use of list parsing, to achieve text filtering operations
>>> import os >>> file_list=os.listdir("/var/log") >>> file_log=[ i for i in file_list if i.endswith(".log") ] >>> print(file_log) ['boot.log', 'yum.log', 'ecs_network_optimization.log', 'ntp.log'] >>> file_log=[ i for i in os.listdir("/var/log") if i.endswith(".log") ] >>> print(file_log) ['boot.log', 'yum.log', 'ecs_network_optimization.log', 'ntp.log']
Next, let's study the generator. The generator is similar to a function whose return value is an array. This function can accept parameters and can be called, but different from the general function, it will return an array containing all values at once. The generator can only produce one value at a time, so the amount of memory consumed will be greatly reduced, and the calling function is allowed to process quickly Several return values, so the generator looks like a function, but behaves like an iterator
Let's first look at the comparison between the following two situations. The first method is very simple. Only by changing the [] bracket of a list generation type to () bracket, a generator is created
>>> lis = [x*x for x in range(10)] >>> print(lis) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> generator = (x*x for x in range(10)) >>> print(generator) <generator object <genexpr> at 0x0000022E5C788A98>
As an example above, the first lis creates a list through list generation, while the second generator prints out a memory address. If we want to get the data in the second variable, we need to iterate as follows:
>>> generator = (x*x for x in range(10)) >>> print(next(generator)) 0 >>> print(next(generator)) 1 >>> print(next(generator)) 4 >>> print(next(generator)) 9
As you can see above, the generator saves the algorithm. Every time it calls next (generatotr), it calculates the value of its next element until it calculates the last element. Using for loop can easily traverse the data in the iterator, because the generator is also an object that can be iterated
>>> generator = (x*x for x in range(10)) >>> >>> for i in generator: print(i,end="") 0149162536496481
The generator expression does not really create a list of numbers, but returns a generator object. This object "yields" this item every time it calculates an item. The generator expression uses "lazy calculation" or a mechanism sequence called "delayed evaluation" which is too long. When only one element needs to be obtained each time, we should consider using the generator expression instead of list parsing
>>> import sys >>> >>> yie=( i**2 for i in range(1,10) ) >>> next(yie) 1 >>> next(yie) 4 >>> next(yie) 9 >>> for j in ( i**2 for i in range(1,10)):print(j/2)
Practice examples: generate several generators through functions, and yield keywords
>>> import sys >>> >>> def func(): yield 1 yield 2 yield 3 yield 4 yield 5 >>> temp=func() >>> temp.__next__() 1 >>> temp.__next__() 2 >>> temp.__next__() 3
Exercise example: use while loop to build a generator and print the result through for traversal
>>> import sys >>> >>> def yieldNum(x): y=0 while (y <= x): yield y y += 1 >>> yie=yieldNum(5) >>> for i in yie: print(i)
Exercise example: use the generator to square 1 - 10
>>> def yieldNum(): x=1 while (x <=10 ): yield x ** 2 x += 1 >>> yie=yieldNum() >>> >>> for i in yie: print(i)
Exercise example: use generator to implement range function
>>> def xrange(num): temp=-1 while True: temp=temp+1 if (temp >= num): return else: yield temp >>> xrange(10) <generator object xrange at 0x038E3030>
Example: find Fibonacci series by using generator
>>> def fib(max): n,a,b=0,0,1 while n < max: yield b a,b=b,a+b n+=1 return "done" >>> f=fib(5) >>> f <generator object fib at 0x038F4A20>
Exercise example: use generator to achieve concurrent effect in the case of a single process
import time def consumer(name): print("%s Ready to eat steamed buns!" %name) while True: baozi = yield print("Steamed stuffed bun[%s]Coming,cover[%s]Ate!" %(baozi,name)) def producer(name): c = consumer('A') c2 = consumer('B') c.__next__() c2.__next__() print("I'm getting ready to make steamed buns!") for i in range(10): time.sleep(1) print("Made two buns!") c.send(i) c2.send(i) producer("alex")

subset: commoncrawl