Strings, lists of strings, generate dictionaries in reverse order.

A string with a number generates a dictionary in reverse order with the number as the key, and a list of strings generates a dictionary in reverse order with its element index as the key.


【The details of learning is a joyful process】

  • Python official website: python cutting edge. It’s a pity that it’s the original English version. So, I want to practice English reading. ” rel=”noopener noreferrer”>https://www.python.org/

  • Free: Big coffee free “The Bible” tutorial “Python Complete Self-study Tutorial“, not just the basics…
    Address: https://lqpybook.readthedocs.io/

Self-study is not something mysterious, a person always spends more time in self-study than in school, and there are always more times when there is no teacher than when there is a teacher.
Hua Luogeng

  • My CSDN homepage, My HOT blog, My Python learning personal memo
  • Highly recommended, Old Qi Classroom


Waiting for the wind to come, it is better to chase the wind...


A string with numbers generates a dictionary in reverse order with numbers as keys


The string generates a dictionary according to the rules


(The string list generates a dictionary in reverse order according to its element index as key)

The quality score of this article:


91
Address of this article:
https://blog.csdn.net/m0_57158496/article/details/130809903

CSDN quality score query entrance: http://www.csdn.net/qc


Directory?Directory

  • ◆? String & amp; list of strings to generate a dictionary according to the rules
    • 1. Description of the topic
    • 2. Problem-solving ideas
      • 2.1 Disassembly of the topic
      • 2.2 Screenshot of code running effect
    • 3. Problem-solving operation
      • 3.1 string list
      • 3.2 code text with numbers
    • 4. Complete source code

◆? String & amp; list of strings generates a dictionary according to the rules

1. Title description

(The title comes from the CSDN question and answer community question “Python implements an inverted index”).

There is no code text for the title, I use an unfinished “engineering” code text to test–


back page catalog

2. Problem-solving ideas

2.1 Disassembly of the topic

The reverse index of the list string generates a dictionary for the key, which is relatively simple. There is no requirement in the title, the list can be reversed first, and then its length n- its element index is the key, and the string element is the value. There are many ways to choose from, and you can pick up your favorite beans. About the reverse sequence, I have made study notes “Python list (list) reverse (descending) 7 implementations”, you can click on the blue text to jump to read.
Strings with serial numbers, I feel a little tricky with my current Python skills. The conceivable method is to use re to extract the numbers, use str.split() to traverse the strings after the numbers intercepted from the back to the front with the numbers as symbols, and use the numbers as keys and strings as values to append to the dictionary in turn. Since it is operated from back to front, the result is reverse order.

Use the content of the code text file1.py that I have not completed to disassemble the topic and clarify the thinking–

  • file1.py content
#!/sur/bin/nve python
# coding: utf-8
from re import findall
my_path = '/sdcard/Documents/'
names_text_line = open(f"{my_path}Romance of the Three Kingdoms character list.txt").readlines()
texts = open(f"{my_path}Three Kingdoms.txt").read()
names = []
name_sort = {<!-- -->}

for i in names_text_line:
    print(i)
    name = findall(r'([^A-Z][\\一-\\龥(,) \(\)] + )[, \\
] + ', i)
    name = [i if ', ' not in i else i.split(', ') for i in name]
    
    input(f"Local_name: {name}")

for i in names:
    if len(i)==1:
        print(i)
input(999)

for k,name in enumerate(names):
    print(' '*50, end='\r')
    print(f"{' '*(k9)}finding ...", end='\r')
    name_sort[name] = texts. count(name)

print(' '*50, end='\r')
print(f"\\
Cao Cao: {'Cao Cao' in names},{name_sort.get('Cao Cao', None)}")
names = [(name, times) for name, times in name_sort.items()]
names.sort(key=lambda x: x[1], reverse=True)

for i in range(20):
    print(f"{names[i][0]:>18}:{names[i][1]}")

print(len(names), len(name_sort), len(texts))

  • Generating strings and lists of strings from code text
lis = open('/sdcard/qpython/file1.py').readlines()[:17] # Read the code text and generate a string list with each line string as an element.
mystr = ' '.join([f"{k}: {i[:-1]}" for k,i in enumerate(lis)]) # splicing the code text into one character with line number string.

2.2 Screenshot picture of code running effect




back page catalog

3. Problem solving operation

3.1 string list

  • For a list of strings, just parse it in reverse order
lis_dict = {<!-- -->str(i): lis[i] for i in range(len(lis)-1, -1, -1)} # Dictionary analysis generates a result dictionary.

3.2 code text with numbers

  • extract numbers from string
mystr_indexs = findall(r'\d + : ', mystr) # The re.findall() method extracts a list of line numbers.

  • loop split append to dictionary
for i in range(len(mystr_indexs)-1, -1, -1): # The loop splits the string lines in reverse order and appends them to the dictionary.
    temp = mystr2. split(f"{i}:")
    mystr_dict[f"{i}"] = temp[1]
    mystr2 = temp[0]


back page catalog

4. Complete source code

(The source code is long, click here to skip the source code)

#!sur/bin/nve python
# coding: utf-8
from re import findall

lis = open('/sdcard/qpython/file1.py').readlines()[:18] # Read the code text and generate a string list with each line string as an element.
mystr = ' '.join([f"{k}: {i[:-1]}" for k,i in enumerate(lis)]) # splicing the code text into one character with line number string.

mystr_indexs = findall(r'\d + : ', mystr) # The re.findall() method extracts a list of line numbers.
mystr_dict = {<!-- -->} # The initial value of the code line string dictionary.
mystr2 = mystr

for i in range(len(mystr_indexs)-1, -1, -1): # The loop splits the string lines in reverse order and appends them to the dictionary.
    temp = mystr2. split(f"{i}:")
    mystr_dict[f"{i}"] = temp[1]
    mystr2 = temp[0]

print(f"\\
string:\\
'{mystr}'\\
\\
generated dictionary:\\
{mystr_dict}") # Result output.

lis_dict = {<!-- -->str(i): lis[i] for i in range(len(lis)-1, -1, -1)} # Dictionary analysis generates a result dictionary.
print(f"\\
\\
string list:\\
'{lis}'\\
\\
generated dictionary:\\
{lis_dict}") # Result output.


back to top

Last article:? Code to simulate Spring Festival “collecting five blessings” , to realize the process of simulating the collection of five blessings during the Spring Festival)
Next:?

My HOT blog:

A total of 210 blog post notes were collected this time, with a total reading volume of 33.91w and an average reading volume of 1614. 22 blog post note index links with at least 3,000 readings have been generated. Data collection was completed at 2023-05-22 05:29:13, taking 4 minutes and 49.29 seconds.

  1. The magical code that changes the nickname of QQ group
    ( 54591 read)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/122566500
    Likes: 24 Dislikes: 0 Favorites: 80 Rewards: 0 Comments: 17
    The notes for this blog post were first published at 2022-01-18 19:15:08 and revised at the latest at 2022-01-20 07:56:47.
  2. First experience of ChatGPT domestic mirror station: chat, Python code generation, etc.
    ( 52131 read)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/129035387
    Likes: 123 Dislikes: 0 Favorites: 788? Rewards: 0 Comments: 75
    The notes for this blog post were first published at 2023-02-14 23:46:33 and revised at the latest at 2023-03-22 00:03:44.
  3. DataFrame of pandas data type
    ( 8313 read)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/124525814
    Likes: 6 Dislikes: 0 Favorites: 25 Rewards: 0 Comments: 0
    The notes for this blog post were first published at 2022-05-01 13:20:17 and revised at the latest at 2022-05-08 08:46:13.
  4. Roman Numeral Converter | Roman Numeral Generator
    ( 6457 read)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/122592047
    Likes: 0 Dislikes: 0 Favorites: 1 Rewards: 0 Comments: 0
    The notes for this blog post were first published at 2022-01-19 23:26:42 and revised at the latest at 2022-01-21 18:37:46.
  5. Python string is displayed in the center
    ( 6277 read)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/122163023
    Likes: 1 Dislikes: 0 Favorites: 5 Rewards: 0 Comments: 1
    The notes for this blog post were published at 2021-12-26 23:35:29.
  6. Personal information extraction (string)
    ( 5886 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/124244618
    Likes: 0 Dislikes: 0 Favorites: 9 Rewards: 0 Comments: 0
    This blog post note was first published at 2022-04-18 11:07:12, and was revised at 2022-04-20 13:17:54 at the latest.
  7. Recursive implementation and for implementation of Fibonacci sequence
    ( 5308 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/122355295
    Likes: 4 Dislikes: 0 Favorites: 2 Rewards: 0 Comments: 8
    Notes for this blog post were published at 2022-01-06 23:27:40.
  8. Exercise: String statistics (pit: f’string’ reports an error)
    ( 4892 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/121723096
    Likes: 0 Dislikes: 0 Favorites: 1 Rewards: 0 Comments: 0
    The notes for this blog post were published at 2021-12-04 22:54:29.
  9. Exercise: Nim game (smart version/fool style? Man-machine battle)
    ( 4632 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/121645399
    Likes: 14 Dislikes: 0 Favorites: 42 Rewards: 0 Comments: 0
    The notes for this blog post were published at 2021-11-30 23:43:17.
  10. Carriage Return, Line Feed, and Carriage Return Line Feed
    ( 4427 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/123109488
    Likes: 0 Dislikes: 0 Favorites: 2 Rewards: 0 Comments: 0
    This blog post note was first published at 2022-02-24 13:10:02, and was revised at 2022-02-25 20:07:40 at the latest.
  11. python clear screen
    ( 4406 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/120762101
    Likes: 0 Dislikes: 0 Favorites: 5 Rewards: 0 Comments: 0
    The notes for this blog post were published at 2021-10-14 13:47:21.
  12. Seven implementations of reverse (descending) order of Python list (list)
    ( 4268 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/128271700
    Likes: 4 Dislikes: 0 Favorites: 14 Rewards: 0 Comments: 8
    The notes for this blog post were first published at 2022-12-11 23:54:15 and revised at the latest at 2023-03-20 18:13:55.
  13. Password Strength Checker
    ( 3924 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/121739694
    Likes: 1 Dislikes: 0 Favorites: 4 Rewards: 0 Comments: 0
    The notes for this blog post were first published at 2021-12-06 09:08:25 and revised at the latest at 2022-11-27 09:39:39.
  14. Roman numeral converter (implemented by modulo of the value of the Roman numeral construction element)
    ( 3840 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/122608526
    Likes: 0 Dislikes: 0 Favorites: 0 Rewards: 0 Comments: 0
    This blog post note was first published at 2022-01-20 19:38:12, and was revised at 2022-01-21 18:32:02 at the latest.
  15. Exercise: Generate 100 random positive integers
    ( 3740 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/122558220
    Likes: 1 Dislikes: 0 Favorites: 4 Rewards: 0 Comments: 0
    The notes for this blog post were first published at 2022-01-18 13:31:36 and revised at the latest at 2022-01-20 07:58:12.
  16. Exercise: Is it difficult for someone in my class to have the same birthday as me? (probability probability, Monte Carlo stochastic simulation method)
    ( 3588 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/124424935
    Likes: 1 Dislikes: 0 Favorites: 2 Rewards: 0 Comments: 0
    The notes for this blog post were first published at 2022-04-26 12:46:25 and revised at the latest at 2022-04-27 21:22:07.
  17. My Python.color() (Python color printing control)
    ( 3470 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/123194259
    Likes: 2 Dislikes: 0 Favorites: 7 Rewards: 0 Comments: 0
    The notes for this blog post were first published at 2022-02-28 22:46:21 and revised at the latest at 2022-03-03 10:30:03.
  18. Exercise: Simulate Welfare Lottery Shuangseqiu-how hard is it to win the 500w jackpot? Just run the code and you will know.
    ( 3258 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/125415626
    Likes: 3 Dislikes: 0 Favorites: 4 Rewards: 0 Comments: 3
    This blog post note was first published at 2022-06-22 19:54:20, and was revised at 2022-06-23 22:41:33 at the latest.
  19. Chat message sensitive word shielding system (string replacement str.replace(str1, *) )
    ( 3125 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/124539589
    Likes: 3 Dislikes: 0 Favorites: 2 Rewards: 0 Comments: 3
    This blog post note was first published at 2022-05-02 13:02:39, and was revised at 2022-05-21 06:10:42 at the latest.
  20. The meaning of the special comment symbol (combination of pound sign and exclamation mark) in the first line of the Linux script file
    ( 3089 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/123087606
    Likes: 0 Dislikes: 0 Favorites: 4 Rewards: 0 Comments: 3
    The notes of this blog post were first published at 2022-02-23 13:08:07 and revised at the latest at 2022-04-04 23:52:38.
  21. Exercise: Find the balance point of the list (list of integers)
    ( 3034 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/121737612
    Likes: 0 Dislikes: 0 Favorites: 0 Rewards: 0 Comments: 0
    The notes for this blog post were published at 2021-12-05 23:28:10.
  22. random.sample() will be deprecated in subsequent versions of python 3.9x
    ( 3000 reads)
    Blog post address: https://blog.csdn.net/m0_57158496/article/details/120657230
    Likes: 0 Dislikes: 0 Favorites: 0 Rewards: 0 Comments: 0
    The notes for this blog post were published at 2021-10-08 18:35:09.


Recommendation conditions
The number of readings exceeded 3,000


(For more hot blogs, please click the blue text to jump to read)


back to top



Old Qi cartoon head

High-quality articles:

  • Good article recommended:Qi Wei’s Manuscript “Python Complete Self-study Course” FreeSerial(The manuscript has been completed and assembled into a book, and there is also a PDF version for permanent sharing on Baidu Netdisk. Click Jump to download for free.)
  • Three major characteristics of OPP: property in the package
  • Understanding python’ through built-in objects
  • regular expression
  • The role of “*” in python
  • The Complete Self-Study Workbook for Python
  • walrus operator
  • `!=` is not the same as `is not` in Python
  • The Right Way to Learn Programming

Source: Lao Qi Classroom


back to top

◆ Python Getting Started Guide 【Python 3.6.3】

Highly recommended for good writing:

  • A high-quality creator in the full-stack field–[Han Lao](Still a student in a domestic college)Blog post “Non-technical article-about English and how to “Correct questioning”, “English” and “being able to ask questions” are two powerful tools for programming learning.
  • [Fields of application of the 8 major programming languages] Don’t worry about choosing linguistics programming, first see what they can do
  • Good habits of reliable programmers
  • Daxie Shuaidi’s high-quality and good article “function function, end condition, function equivalence” three elements let you recognize recursion

CSDN practical skills blog post:

  • 8 practical Python skills that are easy to use
  • python ignore warning
  • Python code writing specification
  • Python’s docstring specification (the standard way to describe the document)