Home >> Python >> Standard Libraries


■標準ライブラリ(モジュール)のいくつかの紹介

☆乱数


	# random number
	
	import random
	print( random.random() )
	print( random.uniform( 1, 10 ))
	print( random.randint( 1, 10 ))
	print( random.randrange(0, 101, 2))
	print( random.choice( "ABCDEFG"))
	items = range( 1, 11 )
	random.shuffle( items )
	print( items )
	
	# generate 100 numbers by randomized
	# number between 1 and 100
	
	result = []
	for i in range(100):
		result = result +  [ random.randint(1, 100)]
	print( result )
	print( max(result), min(result))
	print( sum(result)*1.0/ len(result) )

	
	
	# sort randomized list

	import random
	xlist = [ ]
	for i in range( 100 ):
		xlist += [ random.randint(1, 100) ]
	
	ylist = sorted( xlist )
	print( ylist )

	# make histogram
	
	histogram = [0]*11
	for i in ylist:
		index = i//10
		histogram[ index ] += 1
	print( histogram )

	

☆多精度実数

	
	#整数は多桁で表現されているが、実数は17桁の精度
	
	print( 111111111111111111111111 ** 2 )
	print( "%.17f" % (0.70 * 1.05) )
	
	# Decimal (Precise real number)

	from decimal import *
	getcontext().prec = 80  # 精度を80桁で指定
	a = Decimal( "0.70")
	b = Decimal( "1.05")
	print( "%.17f" % (a*b) )
	a = Decimal( "1.0")
	b = Decimal( "3.0")
	print( a/b*b )
	print( b.sqrt() )
	print( Decimal( "2.0").sqrt())
	
	

☆インターネットやファイルのアクセス

	
	# internet access
	import urllib2
	for line in urllib2.urlopen( "http://www.apple.com"):
		if "href" in line:
			print( line )
	
	# file access
	f = open( "module19.py", "r")
	for line in enumerate(f,1):
		print( line )
	
	

☆スレッド

Python 3.0以降は、threadクラスが_threadクラスになり、内部的なものとして処理 されています。そのため、threadingモジュールのThreadクラスを使って書き直しました。 スレッドの終了を待つために、Thread.joinメソッドを用いています。

	
	#Thread Tester
	
	from threading import Thread
	import time
	
	class ThreadTester(Thread):
		def run(self):
			for i in range(1,10):
				time.sleep(0.5)
				print( i )
	
	
	tt = ThreadTester()
	tt.start()
	Thread.join(tt)
	print( time.ctime() )

	

前出のPython 2.xまで使われていたthreadモジュールですが、Python 3.0以降では、 _threadという名前に変えて、まだ健在です。

	
	# native thread

	import time
	import _thread # Python 2.xでは、thread
	
	def runner():
		for i in range( 20 ):
			print( time.ctime() )
			time.sleep(1)
		print( "Thread Terminated" )
		_thread.exit() # Python 2.xでは、thread.exit( )
	
	_thread.start_new_thread( runner, () ) # Python 2.xでは、thread
	time.sleep(5)
	print( "Main Program Terminated" )
	
	

AlgorithmsPython PyQt First