本文整理汇总了Python中ast.make_tuple函数的典型用法代码示例。如果您正苦于以下问题:Python make_tuple函数的具体用法?Python make_tuple怎么用?Python make_tuple使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了make_tuple函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: createAllResearchTraining
def createAllResearchTraining():
#Initialize empty lists to store all of the relevant information.
imageNames = []
CoordLeft = []
CoordRight = []
SpeciesList = []
NumFlowers = []
#with open('Research Map Data Association - Sheet1.csv', 'rb') as csvfile:
with open('EditedResearchMapData.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter = ',')
i = 0
for row in reader:
if i == 0: #throw out the first row.
print(i)
elif len(row)<8:
print("Row too short")
else:
print(row)
if row[2] == '' or row[3] == '' or row[4] == '' or row[5] == '' or row[7] == '':
print('missing information')
else:
imageNames += [IMAGE_PATH + row[2] + '.jpg']
tupleLeft = make_tuple('(' + row[3] + ')')
CoordLeft += [tupleLeft]
tupleRight = make_tuple('(' + row[4] + ')')
CoordRight += [tupleRight]
SpeciesList += [row[5]]
NumFlowers += [float(row[7])]
i += 1
return imageNames, CoordLeft, CoordRight, SpeciesList, NumFlowers
示例2: run
def run(bump):
while True:
command = raw_input("Command: ")
if command == 'q':
exit(0)
elif command == 'c':
print "right:", bump.getRightArmCoords()
print "left:", bump.getLeftArmCoords()
elif command[0] == 'l':
bump.moveLeftArmTo(make_tuple(command[1:]))
elif command[0] == 'r':
bump.moveRightArmTo(make_tuple(command[1:]))
elif command[0] == 'b':
coords = make_tuple(command[2:])
if command[1] =='r':
bump.bumpRight(coords)
elif command[1] =='l':
bump.bumpLeft(coords)
else:
print "Unknown command"
elif command[0] == 'w':
angle = make_tuple(command[2:])
if command[1] == 'l':
bump.rotateLeftWristTo(angle)
elif command[1] == 'r':
bump.rotateRightWristTo(angle)
else:
print "Unknown command"
else:
print "Unknown command"
示例3: play
def play(self):
print("How to play:\nExample: (x,y,z) to (x1,y1,z1)\nExample: KP0 to QP1")
while True:
self.board.pretty_print()
do_move = True
while do_move:
(a, b) = input("White's Move:").split(" to ")
try:
if a[0] in ("K", "Q"):
self.board.move_atk_board(a, b)
else:
self.board.move(make_tuple(a), make_tuple(b))
do_move = False
except InvalidMoveException as err:
print(err)
do_move = True
self.board.pretty_print()
while do_move:
(a, b) = input("Black's Move:").split(" to ")
try:
if a[0] in ("K", "Q"):
self.board.move_atk_board(a, b)
else:
self.board.move(make_tuple(a), make_tuple(b))
do_move = False
except InvalidMoveException as err:
print(err)
示例4: getTypeFromData
def getTypeFromData(self,_data):
if self.variableType=="dynamic":
if _data.attrib.has_key('type'):
self.variableType = _data.attrib['type']
else: self.variableType = 'string'
if self.variableType=="string": return _data
if self.variableType=="int": return int(_data)
if self.variableType=="float": return float(_data)
if self.variableType=="bool": return (_data.lower() == 'true')
if self.variableType=="tuple": make_tuple(_data)
示例5: onOk
def onOk(self):
if DEBUG:
print >> sys.stderr, "values are:",
print >> sys.stderr, self.sp.get(),
print >> sys.stderr, self.ep.get(),
print >> sys.stderr, self.d.get(),
print >> sys.stderr, self.s.get()
sp = make_tuple(self.sp.get())
ep = make_tuple(self.ep.get())
d = int(self.d.get())
s = int(self.s.get())
self.top.destroy()
self.culebron.drag(sp, ep, d, s)
示例6: __init__
def __init__(self, config, communicator, defects, travel_time):
self.communicator = communicator
self.leaky_battery = ('True' == defects['leaky_battery'])
if self.leaky_battery:
print("The battery is set to leak")
self.uuid = config.get('uuid')
self.real_battery_size = config.getfloat('battery_size')
self.battery_size = self.real_battery_size
self.initial_location = Point(*make_tuple(config.get('c2_location')))
self.location = Point(*make_tuple(config.get('start_location')))
self.location_lock = asyncio.Lock()
self.start_time = 0
self.travel_time = travel_time
self.battery_id = 0
示例7: start_stream
def start_stream():
stop_event = threading.Event()
var_start_h.get()
var_start_m.get()
var_end_h.get()
var_end_m.get()
time_interval = (int(var_start_h.get()), int(var_start_m.get()), int(var_end_h.get()), int(var_end_m.get()))
writeToFile("time_schedule.in", time_interval)
if not check_times(time_interval):
print time_interval
print "Error in data_scheduler, wrong format in the file."
return
if start_interval_reached(time_interval[0], time_interval[1]):
time = calculate_time(time_interval[0], time_interval[1])
print time
threading.Timer(time, get_continuously_data, [make_tuple(str(time_interval))]).start()
while not stop_event.is_set():
if (end_interval_reached1(time_interval[2], time_interval[3], 3)):
show_piechart_now(time_interval)
stop_event.set()
示例8: recipe_read
def recipe_read(recipe: dict) -> tuple:
bright, ttime, pause_time = recipe
if type(bright) is str and bright[0:3] in 'rnd':
val = make_tuple(bright[3:])
val = (val[0], val[1]) if (val[0] < val[1]) else (val[1], val[0])
bright = random.randint(*val)
return bright, ttime, pause_time
示例9: generate_data_set
def generate_data_set(args):
data_file = args.data
location_file = args.locations
locations = dict()
with open(location_file, 'r') as f:
for line in f:
addr, loc = line.strip().split(':')
locations[addr.strip()] = make_tuple(loc.strip())
uniq_set = set()
with open(data_file, 'r') as f:
lines = (line.strip() for line in f)
count = 0
for line in lines:
count += 1
if count == 1:
continue
info = parse_restaurant_info(line)
key = '%s, %s' % (info['addr'], info['zipcode'])
signature = '%s:%s:%s' % (info['name'], info['addr'], info['zipcode'])
if key in locations and signature not in uniq_set:
info['location'] = locations[key]
json_obj = json.dumps(info, ensure_ascii=False)
uniq_set.add(signature)
print json_obj
示例10: test_basics
def test_basics(self):
# Setup the files with expected content.
temp_folder = tempfile.mkdtemp()
self.create_file(os.path.join(temp_folder, 'input.txt'), FILE_CONTENTS)
# Run pipeline
# Avoid dependency on SciPy
scipy_mock = MagicMock()
result_mock = MagicMock(x=np.ones(3))
scipy_mock.optimize.minimize = MagicMock(return_value=result_mock)
modules = {
'scipy': scipy_mock,
'scipy.optimize': scipy_mock.optimize
}
with patch.dict('sys.modules', modules):
from apache_beam.examples.complete import distribopt
distribopt.run([
'--input=%s/input.txt' % temp_folder,
'--output', os.path.join(temp_folder, 'result')])
# Load result file and compare.
with open_shards(os.path.join(temp_folder, 'result-*-of-*')) as result_file:
lines = result_file.readlines()
# Only 1 result
self.assertEqual(len(lines), 1)
# parse result line and verify optimum
optimum = make_tuple(lines[0])
self.assertAlmostEqual(optimum['cost'], 454.39597, places=3)
self.assertDictEqual(optimum['mapping'], EXPECTED_MAPPING)
production = optimum['production']
for plant in ['A', 'B', 'C']:
np.testing.assert_almost_equal(production[plant], np.ones(3))
示例11: open_model_file
def open_model_file(file_name):
with open(file_name) as data_file:
model = json.load(data_file)
print 'read model!'
model = {make_tuple(str(key)): value for key, value in model.iteritems()}
print 'convert model!'
return model
示例12: main
def main(nouns_loc, word2vec_loc, n_nouns, out_loc):
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s',
level=logging.INFO)
# Load trained Word2Vec model
model = Word2Vec.load(word2vec_loc)
logger.info('Word2Vec object loaded')
logger.info('Keeping %s nouns', n_nouns)
# Empty dictionary for noun to vector mapping
noun_to_vect_dict = {}
# Counter to know when to stop
counter = 0
with open(nouns_loc, 'r') as f:
while counter < int(n_nouns):
line = make_tuple(f.readline())
# Add noun and vector to mapping dictionary
noun = line[0]
noun_to_vect_dict[noun] = model[noun]
# Increment counter
counter += 1
logger.info('Pickling noun to vector dictionary')
# Pickle dictionary
with open(path.join(out_loc, 'noun_to_vect_dict_' + n_nouns + '.pkl'), 'w') as f:
pickle.dump(noun_to_vect_dict, f)
示例13: handle
def handle(self, *args, **options):
def _save_product(product_data):
# print(product_data)
product, created = Product.objects.get_or_create(
name=product_data[1],
description = product_data[2],
price = product_data[3],
discounted_price = product_data[4],
image = product_data[5],
image_2 = product_data[6],
thumbnail = product_data[7],
display = product_data[8]
)
print(product)
if created:
product.save()
return product
with open('tmp/data/products.json', 'r') as f:
data = f.readlines()
for row in data:
row_data = row.strip()
tuple_data = make_tuple(row_data)
try:
# print(tuple_data[0])
product = _save_product(tuple_data[0])
print("Product created :"+product)
except Exception:
print("Error")
#Save the product here
示例14: results
def results():
# prevent css caching
rand = random.randint(0,2500000)
c_cache = "../static/css/colors.css?" + str(rand)
cols = request.args.get('main_cols')
pallete = request.args.get('p_cols')
tups = make_tuple(cols)
tlist = []
hlist = []
for t in tups:
tlist.append(t[1])
hlist.append('%02x%02x%02x' % t[1])
primcol = tlist[0]
hcol = '%02x%02x%02x' % primcol
print("results pallete: %s" % pallete)
state = 'ran'
return render_template('results.html',
title='tagbar',
hashtag=request.args.get('tag'),
colors=cols,
primary=primcol,
hexcol=hcol,
hcs = hlist,
pcl=pallete,
dt=c_cache)
示例15: make_reservation
def make_reservation(self):
reservation_name = input("Choose name: ")
number_of_tickets = input("Choose number of tickets: ")
self.show_movies()
while True:
reservation_movie_id = input("Choose movie id: ")
self.__cinema.get_num_of_free_seats_by_movie_id(
reservation_movie_id)
wanted_projection_id = input("Choose projection id: ")
if self.how_many_free_seats(reservation_movie_id, number_of_tickets):
break
else:
print("There are no more available seats! Enter new id: ")
list_of_not_available_seats = self.__cinema.show_all_available_spots_matrix(
wanted_projection_id)
matrix = self.matrix_print(list_of_not_available_seats)
count = 0
list_of_reserved_seats = []
while int(count) < int(number_of_tickets):
seat_tuple_str = input("Choose a seat: ")
seat_tuple = make_tuple(seat_tuple_str)
if int(seat_tuple[0]) > 10 or int(seat_tuple[0]) < 1 or int(seat_tuple[1]) > 10 or int(seat_tuple[1]) < 1:
print("There is no such seat")
elif matrix[int(seat_tuple[0]) - 1][int(seat_tuple[1]) - 1] == 'X':
print("This seat is taken")
else:
count += 1
list_of_reserved_seats.append(seat_tuple)
res = {}
res["res_name"] = reservation_name
res["list_of_seats"] = list_of_reserved_seats
res["projection_id"] = wanted_projection_id
print("If you want to save your reservation type finalize")
return res