python exercises --2

1, determines whether there are duplicate characters in list

Ideas: to re-set by, and then compare list length, repeatedly returns False, True return will not be repeated

# Check for duplicate elements 
DEF check_repeat (List):
     return len (List) == len (the SET (List))

2, the two strings are equal number of times each character appears, the order may be different

counter method can count the number of occurrences of characters

# Detect whether two strings anagram each other (i.e., reversing the order of each character) 
from Collections Import Counter
 DEF counter_str (First, SECOND):
     return Counter (First) == Counter (SECOND)

3, in order to return a string of bytes Unit

Thinking: string encoding format to UTF-8, then the statistics length

# Bytes returns the string length 
DEF byte_size (STR):
     return   len (str.encode ( ' UTF-. 8 ' )) # a character 3 bytes

4. Repeat the print string

Ideas: multiplied by n, to achieve the effect of multiple

# Repeated N times the print string 
n-=. 7 
STR = ' Zhao ' 
Print (n-STR *)

5, a string capitalize the first letter of each word

# Initials, a string for each word capitalized 
S = ' COUNT your Awesome ' 
Print (s.title ()) # each word string within the initials

6, delete the list of errors in the data

bool function, the number of errors is FALSE, 0, none, filter corresponding to the iterator, the list is transmitted to each value method bool

# The following method uses fliter () error value to delete the list (eg: false, none, 0 and "") 
DEF Compact (LST):
     return List (filter (BOOL, LST))
 Print (Compact ([0, 1, false, 2,3, None, 4,5] ))

7, the number of intervals - converting two-dimensional array

Idea: by unpacking function, each of the two-dimensional array array array unpacked reassembled

# Number of intervals - converting a two-dimensional array 
Array = [[ ' A ' , ' B ' ], [ ' C ' , ' D ' ], [ ' E ' , ' F ' ]] 
the transposed = List (ZIP (* Array))
 Print (the transposed) # [( 'A', 'C', 'E'), ( 'B', 'D', 'F')]

8, a list of strings into a single string, each element of the list separated by commas

# List of strings into a single string, each element of the list separated by commas 
hobbies = [ ' your ' , ' Jeans ' , ' Swimming ' ]
 Print ( ' , ' .join (hobbies))

 

Guess you like

Origin www.cnblogs.com/xiaokuangnvhai/p/11613139.html