Home >> Python >> Tutorial on Sequences


Pythonのリスト・部分文字列(スライス)・連想配列

■文字列のスライス

	#String

	xxx = "ABCDEFGHJIKL"
	print( xxx )
	print len(xxx) )
	print( xxx[0] )
	print( xxx[2:] )
	print( xxx[:2] )
	print( xxx[3:6] )
	print( xxx[3:8] )
	print( xxx[-1] )
	print( xxx[-3:] )
	print( xxx[-3:-1] )
	print( xxx + "MNOPQRSTU" )
	print( xxx * 3 )
	xxx = xxx + "MNOPQRSTUVWXYZ"
	print( xxx )
	

■リストとスライス

	#List

	xlist = [ 12, 23, 34, 45, 56, 67, 78, 89]
	print ( xlist )
	print( xlist[0] )
	print( xlist[1:5] )
	print( xlist + [99, 100] )
	print( xlist * 2
	print len( xlist )
	xlist.append(2222)
	print( xlist )
	xlist.insert(2, 99)
	print( xlist )
	xlist = xlist * 2
	xlist.remove( 56 )
	print( xlist )
	ylist = [ "7834", 5765, True, 56.9 ]
	print( ylist )
	print( range(10) )
	print( range(2,19) )
	print( range(10, 110, 10) )
	ylist[:0]=ylist
	print( ylist )
	ylist[:0]=[xlist]
	print( ylist )
	ylist[0]=[]
	print( ylist )
	zlist = list( )
	

リストのステップなど

		
	# slice by steps
	
	xlist = [ 23,43,45,65,67,23,54,98 ]
	print( xlist[::2])
	print( xlist[::-2])
	
	# function for list
	
	print( sum( xlist ))
	print( sorted(xlist))
	rlist = list( reversed(xlist) )
	print( rlist )
	
	#enumurate
	
	ylist = ["Spring","Summer", "Autumn","Winter"]
	for i, season in enumerate( ylist ):
		print( i, season )
	x, y = divmod( 200,36 )
	print(x, y, x*36+y )
	

■集合(Set)

	# set type
	xxx = ["Hello", "Good bye", "Good morning"]
	yyy = ["Apple", "Orange", "Hello"]
	print set( xxx )
	if "Good bye" in set( xxx ):
		print( "See you.")
	zzz = set(xxx) | set( yyy ) # A or B
	www = set(xxx) & set( yyy ) # A and B
	xor = set(xxx) ^ set( yyy ) # A xor B
	print( zzz )
	print( www )
	print( xor )
	
	

■辞書(Dictionary):連想配列

	
	# dictionary
	
	address = {"Smith":["Tokyo", 23 ],  "Satoh": ["Yokohama", 34 ], \
		"Brown": ["Nagasaki", 40], "John":["Toyama", 27]}
	
	print address["Satoh"]
	print address["Brown"][0]
	print address["John"][1]
	print address.keys()
	if address.has_key("John"):
	    address["John"][1]=28
	print address["John"]
	
	tel = dict( smith=345567, john=374758, william=489287, kent=635793 )
	print( tel )
	square = dict([(x,x**2) \
		for x in range(1, 21)])
	print( square )
	alphabet = dict([(unichr(x),x) for x in range(0x30, 0x7f)])
	for x, y in alphabet.iteritems():
		print( "[", x, hex(y), "]", end= " " )
	print( )
	print( hex(alphabet["a"]) )
	
	

■Iterator

	
	# iterator for string
	
	s = "ABCDEFGHIJK"
	it = iter( s )
	for i in s:
		print( it.next() )
	
	# iterator for list
	
	xlist = [ "John", "Sarry", "Mary", "Kent", "William" ]

	it = iter( xlist )
	for i in range( len( xlist ) ):
		member = it.next(  )
		print( member )
		
	# iterable完成版(try文で)
	
	they = reversed( sorted( xlist ) )
	while True:
		try:
			member = they.next( )
			print( member )
		except StopIteration:
			break
	
	

ExpressionsPython Control Statements