• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python ast.make_tuple函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中ast.make_tuple函数的典型用法代码示例。如果您正苦于以下问题:Python make_tuple函数的具体用法?Python make_tuple怎么用?Python make_tuple使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了make_tuple函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:cassieburgess,项目名称:Flower-Classification,代码行数:34,代码来源:TrainingSpeciesList.py


示例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"
开发者ID:duke-iml,项目名称:ece490-s2016,代码行数:30,代码来源:bump.py


示例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)
开发者ID:MrOerni,项目名称:Tredisca,代码行数:28,代码来源:tredisca.py


示例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)
开发者ID:eaglgenes101,项目名称:universalSmashSystem,代码行数:10,代码来源:subaction.py


示例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)
开发者ID:Fuzion24,项目名称:AndroidViewClient,代码行数:14,代码来源:culebron.py


示例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
开发者ID:GPIG5,项目名称:drone,代码行数:15,代码来源:telemetry.py


示例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()
开发者ID:AdrianaMicu,项目名称:Twitter-Device-Statistics,代码行数:26,代码来源:twitterstream.py


示例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
开发者ID:markph0204,项目名称:huelloween,代码行数:7,代码来源:huerecipe.py


示例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
开发者ID:gothamteam,项目名称:planner-backend,代码行数:26,代码来源:redis_data_load.py


示例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))
开发者ID:charlesccychen,项目名称:incubator-beam,代码行数:35,代码来源:distribopt_test.py


示例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
开发者ID:AlanovAibek,项目名称:random_text_generator,代码行数:7,代码来源:generate_random_text.py


示例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)
开发者ID:gushecht,项目名称:noungroups,代码行数:25,代码来源:filter_nouns.py


示例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
开发者ID:rajesh67,项目名称:fullstack-challenge,代码行数:32,代码来源:load_sample_data.py


示例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)
开发者ID:DEGoodman,项目名称:tagbar,代码行数:26,代码来源:views.py


示例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
开发者ID:hrizantema-st,项目名称:Cinema-Reservation-System,代码行数:34,代码来源:cinema_interface.py


示例16: main

def main(config_file):
    oldloop = asyncio.get_event_loop()
    oldloop.close()

    print("Bootstrapping drone configuration")
    config = configparser.ConfigParser()
    config.read(config_file)
    num_drones = int(config["main"]["num_drones"])
    df = config['detection']['data_folder']
    if os.path.exists(df):
        print("deleting data")
        shutil.rmtree(df)
    os.mkdir(df)
    config = None

    print("Generating subconfigurations")
    configs = []
    for i in range(0, num_drones):
        config = configparser.ConfigParser()
        config.read(config_file)
        loc = tuple(
            [float(x) for x in make_tuple(
                config["telemetry"]["start_location"]
            )]
        )
        nloc = (
            loc[0] + (i * 0.0001 * (random.uniform(0, 2) - 1)),
            loc[1] + (i * 0.0001 * (random.uniform(0, 2) - 1)),
            loc[2]
        )
        config["telemetry"]["start_location"] = str(nloc)
        configs.append(config)

    return multi_drone_hybrid(configs)
开发者ID:GPIG5,项目名称:drone,代码行数:34,代码来源:drone.py


示例17: _recv_arrays

    def _recv_arrays(self):
        """Receive a list of NumPy arrays.
        Parameters
        ----------
        socket : :class:`zmq.Socket`
        The socket to receive the arrays on.
        Returns
        -------
        list
        A list of :class:`numpy.ndarray` objects.
        Raises
        ------
        StopIteration
        If the first JSON object received contains the key `stop`,
        signifying that the server has finished a single epoch.
        """
        headers = self.socket.recv_json()
        if 'stop' in headers:
            raise StopIteration
        arrays = []

        for header in headers:
            data = self.socket.recv()
            buf = buffer_(data)
            array = np.frombuffer(buf, dtype=np.dtype(header['descr']))
            array.shape = make_tuple(header['shape'])

            if header['fortran_order']:
                array.shape = header['shape'][::-1]
                array = array.transpose()
            arrays.append(array)

        return arrays
开发者ID:Da-He,项目名称:keras_Realtime_Multi-Person_Pose_Estimation,代码行数:33,代码来源:ds_generator_client.py


示例18: filter_approx_distance

    def filter_approx_distance(self, queryset, value):
        """ Filters all results who's address object has a lat long approximatly value[0] from value[1]
        """
        # Assume value is in the form (distance, lat, long)
        try:
            vals = make_tuple(value)
        except:
            # if something bad happened just fallabck to not working for now
            return queryset

        # remove queryset objects tha have no address
        queryset = queryset.filter(address_object__isnull=False)

        pi = 3.1415
        f_lat = pi*(vals[1] - F('address_object__latitude'))/180.0
        f_long = pi*(vals[2] - F('address_object__longitude'))/180.0
        m_lat = 0.5*pi*(vals[1] + F('address_object__latitude'))/180.0
        cosprox = 1 - (m_lat**2)/2.0 # approximate cosine
        
        approx_dist = (6371**2)*(f_lat**2 + (cosprox*f_long)**2)

        queryset = queryset.annotate(dist=(approx_dist - vals[0]**2)).annotate(flat=f_lat)
        queryset = queryset.filter(dist__lte=0)

        return queryset
开发者ID:data-skeptic,项目名称:home-data-api,代码行数:25,代码来源:filters.py


示例19: get_patch_image

def get_patch_image(filename):
    # we expect the filename format for be patch_(x, y, w, h).png"
    a = "af"    
    dim_str = filename[filename.rindex('('):filename.rindex(')') + 1]
    dim  = make_tuple(dim_str)
    data = matplotlib.image.imread(filename)[:, :, :3] # Use the last 3
    return dim , data
开发者ID:eseaflower,项目名称:ML,代码行数:7,代码来源:count_data_parser.py


示例20: getJourneys

def getJourneys(filename, algorithm):
	"""
	@param filename: name of text file with the following format (space separated) - one journey per line
	<lat> <long> <startTime>
	@param algorithm: should given, start and end node and time, returns a journey
	@return: list of journeys

	startTime should be time in same format as time in crime data
	"""
	journeys = []
	with open(filename) as f:
		lines = f.readlines()
	for line in lines:
		triple = line.split()
		journey = algorithm(make_tuple(triple[0]), make_tuple(triple[1]), triple[2])
		journeys.append(journey)
	return journeys
开发者ID:jshayani,项目名称:Walk-This-Way,代码行数:17,代码来源:simulate.py



注:本文中的ast.make_tuple函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python ast.parse函数代码示例发布时间:2022-05-24
下一篇:
Python ast.literal_eval函数代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap