社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

Devesh Kumar Singh

Devesh Kumar Singh 最近创建的主题
Devesh Kumar Singh 最近回复了
6 年前
回复了 Devesh Kumar Singh 创建的主题 » 如何将iterable赋给python数组变量?

代码中的一些问题

  • 实际上,你可以在输入时对数字求和,而不是在最后

实际上你可以简化你的代码

  1. 您可以将所有数字作为单个字符串的输入
  2. Split 通过使用 string.split
  3. 将每个字符串转换为整数并计算和,同时将整数追加到列表中
  4. 计算平均值并打印
  5. 使用切片反转列表 nums[::-1] 然后打印出来
start = input("Type start if you wan't to do this thang: ")

#If start is inputted, check it and start the loop,
if start.lower() == 'start':
    #Start an infinite loop
    while True:
        #Take 20 numbers separated by single space
        s = input("Enter 20 numbers separated by a single space")

        #List of numbers
        nums = []
        sum = 0

        #Split the string by whitespace, iterate over it and take the sum
        for item in s.split():
            num = int(item)
            nums.append(num)
            sum += int(num)

        #Calcuate the average
        avg = sum/20
        print('Average: ',avg)

        #Reverse the numbers by using reversed function
        nums = list(reversed(nums))

        #Print numbers
        print('The numbers in reverse are ', nums)
        #Check if quit was inputted, if yes break the loop, else continue
        START = input("If that was wild for you, type start again, or type quit if that was lame: ")
        if START == "quit":
            break

输出将如下所示

Type start if you wan't to do this thang: start
Enter 20 numbers separated by a single space1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
Average:  3.0
The numbers in reverse are  [5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1]
If that was wild for you, type start again, or type quit if that was lame: start
Enter 20 numbers separated by a single space1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10
Average:  5.5
The numbers in reverse are  [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
If that was wild for you, type start again, or type quit if that was lame: quit
6 年前
回复了 Devesh Kumar Singh 创建的主题 » Python Dict-多个实例或“Sub Dict”问题-以编程方式添加项

如果我错了就纠正我,但是 host_dict 不是有效的字典,我假设您试图创建一个带键的字典 installed_applications 作为一个列表,它看起来像这样

host_dict = {
    'installed_applications':
    [{
        'name': 'alsdfasdf',
        'version': '1',
        'installed_date': '11-11-11',
    },
    {
        'name': 'alsdfasdf',
        'version': '1',
        'installed_date': '11-11-11',
    },
    {
        'name': 'alsdfasdf',
        'version': '1',
        'installed_date': '11-11-11',
    },
        {
        'name': 'alsdfasdf',
        'version': '1',
        'installed_date': '11-11-11',
    }]
}

在这种情况下,可以通过迭代 apps ,将所需的键值对添加到列表,然后将该列表分配给 钥匙

host_dict = {}
apps = get_installed_apps(host)
host_dict['installed_applications'] = {}

#List to store list of dictionaries
li = []
#Iterate through apps
for app in apps:
    #Create a dictionary for app and append to the list
    dct = {}
    dct['name'] = app[0]
    dct['version'] = app[1]
    dct['uninstall_string'] = app[2]
    dct['install_date'] = app[3]
    dct['install_location'] = app[4]
    dct['publisher'] = app[5]
    li.append(dct)

#Assign the list
host_dict['installed_applications'] = li

或者缩短代码,我们可以

host_dict = {}
apps = get_installed_apps(host)
host_dict['installed_applications'] = {}

#List to store list of dictionaries
li = []

#List of keys for app
app_keys = ['name', 'version', 'uninstall_string', 'install_date', 'install_location', 'publisher']

#Iterate through apps
for app in apps:
    dct = {}
    #Make the dictionary
    for idx, item in enumerate(app):
        dct[app_keys[item]] = item

    li.append(dct)

#Assign the list
host_dict['installed_applications'] = li
6 年前
回复了 Devesh Kumar Singh 创建的主题 » 在python中挣扎于函数的全局定义

import random
import sys


def gen(size):
    # generate...
    return size

def main():
    #Not sure where you are passing pages?
    size = int(sys.argv[1])
    print(size)
    generate = gen(size)
    print(generate)
    print("FIFO", FIFO(size,pages), "page faults.")
    print("LRU", LRU(size,pages), "page faults")
    print ("OPT", OPT(size,pages), "page faults")

def FIFO(self, size, pages):
    return "hello"

def LRU(self, size, pages):
    return "hello"

def OPT(self, size, pages):
    return "hello"

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "Usage: python paging.py [number of pages]"
    else:
        main()

Tohit = random.randrange(12, 32) 分配 Tohit 为整数,但在 if Tohit == "31": Tohit==31 代码应该可以工作:)

此外,您还需要更改 while str(rolls) > str(0): while rolls > 0 while str(critrolls) > str(0) while critrools > 0

还有你的 而critrools>0 是一个无限循环,因为 critrolls = 2 2>0 会导致无限循环,因为你永远不会改变 critrolls 值,您需要在循环中更新该值,或者 critrolls = critrolls - 1

import random
rolls = 2
critrolls = 4
FDMG = 6
DMG = 0
Tohit = random.randrange(12, 32)

#Change to int to int comparison
if Tohit == 31:
    # Change to int to int comparison
    while critrolls > 0:
        DMG = random.randrange(1, 9)
        FDMG = FDMG + DMG
        #Perhaps you need to decrement critrolls here to break infinite loop
        # Change to int to int operation by removing int typecast
        critrolls -= 1
    print("Your to hit is", Tohit)
    print("Your Damage is", FDMG)
elif Tohit <= 30:
    # Change to int to int comparison
     while rolls > 0:
        DMG = random.randrange(1, 9)
        FDMG = FDMG + DMG
        # Change to int to int operation by removing int typecast
        rolls -= 1
     print("Your to hit is", Tohit)
     print("Your Damage is", FDMG)
6 年前
回复了 Devesh Kumar Singh 创建的主题 » 添加到不带引号的python列表

使用 ast.literal_eval 分析字符串 "{'key1': 1, 'key2': 2, 'key3': 3}" 去查字典。

In [16]: import ast                                                                                                                                                                                     

In [17]: classes = {}                                                                                                                                                                                   

In [18]: classes["class1"] = ast.literal_eval("{'key1': 1, 'key2': 2, 'key3': 3}")                                                                                                                      

In [19]: classes                                                                                                                                                                                        
Out[19]: {'class1': {'key1': 1, 'key2': 2, 'key3': 3}}

请注意,您不能使用 json.loads 这里是因为你的字符串中有单引号

In [20]: import json                                                                                                                                                                                    

In [21]: classes = {}                                                                                                                                                                                   

In [22]: classes["class1"] = json.loads("{'key1': 1, 'key2': 2, 'key3': 3}")                                                                                                                            
---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
<ipython-input-22-592615e01642> in <module>
----> 1 classes["class1"] = json.loads("{'key1': 1, 'key2': 2, 'key3': 3}")

JSONDecodeError: Expecting property name enclosed in double quotes: 
line 1 column 2 (char 1)
6 年前
回复了 Devesh Kumar Singh 创建的主题 » 为什么replace()在我的Python函数中不起作用?[副本]

replace 不是就地方法,而是返回新字符串,因此需要将结果分配给新字符串。

从文档中: https://docs.python.org/3/library/stdtypes.html#str.replace

str.replace(旧的,新的[,计数])
返回字符串的副本,所有出现的子字符串old替换为new。如果给定了可选参数计数,则只替换出现的第一个计数。

如果同时迭代键和值,您的逻辑也可以简化很多,如下所示

def replace_exception_chars(string):
    exception_chars_dict = {'Old': 'New', 'old': 'new'}

    #Iterate over key and value together
    for key, value in exception_chars_dict.items():
        #If key is found, replace key with value and assign to new string
        if key in string:
            string = string.replace(key, value)

    return string

print(replace_exception_chars('Old, not old'))

输出将是

New, not new
6 年前
回复了 Devesh Kumar Singh 创建的主题 » 使用Python3以秒为单位显示年龄

你可以用 total_seconds 计算两个日期之间的秒差

from datetime import datetime

year = int(input("year: "))
month = int(input("month: "))
day = int(input("day: "))

#Calculate time in seconds between now and the day of birth
time_in_seconds = (datetime.now() - datetime(year=year, month=month, day=day)).total_seconds()

print("You are {} seconds old.".format(time_in_seconds))

输出将是

year: 1991
month: 1
day: 31
You are 892979995.504128 seconds old.
6 年前
回复了 Devesh Kumar Singh 创建的主题 » Python Read/Parse Account:Password txt逐行文件

你可以使用 csv.reader 模块读取csv文件。

import csv

#Open the file
lines = []
with open('accounts.txt') as fp:

    #Create a csv reader on the file
    reader = csv.reader(fp, delimiter=":")
    #Iterate through each row
    for row in reader:
        lines.append(row)

print(lines)

输出将是

[
['Richard', 'Milo', 'RichardMilo@email.info', '0495612970'], 
['Adrian', 'Clark', 'ClarkAdrian283406@email.info', '0490714484'], ['Michael', 'Robinson', '13Mich@email.info', '0446088017'], 
['Julio', 'Lucas', 'JulioLucas60@email.info', '0454710033']
]

所以第一封邮件是 lines[0][2]

然后要删除文件的内容,只需在 w+ 模式

#Open the file in w+ to delete all rows
filename = "accounts.txt"
f = open(filename, "w+")
f.close()

然后可以将此输出用于 enterraffle() 功能

6 年前
回复了 Devesh Kumar Singh 创建的主题 » 迭代txt文件python

您可以使用临时列表将配料添加到,然后在遇到
一行 - Ingredients: 将这个列表附加到一个更大的列表中,然后再次执行相同的操作。

def get_ingredients_from_file():

    result = []
    with open('file.txt') as fp:
        li = []
        for line in fp:
            #Append the ingredients to temporary list
            if line.startswith('*'):
                li.append(line.replace('*','').strip())
            #Get a new list and append it to result
            elif line.startswith("- Ingredients"):
                li = []
                result.append(li)
    return result

print(get_ingredients_from_file())

如果文件看起来像

- Pasta Salad
- Description:
    bla
    bla

- Ingredients:
* ingredient 1
* ingredient 2
* ingredient 3

- Preperation:
    bla
    bla
    bla

- Ingredients:
* ingredient 4
* ingredient 5
* ingredient 6

输出将看起来像

[['ingredient 1', 'ingredient 2', 'ingredient 3'], 
['ingredient 4', 'ingredient 5', 'ingredient 6']]

itertools.product 0.0.0.0 255.255.255.255

import itertools

li = range(0,256)

#Generate all possible combinations of numbers from 0 to 255, in a pair of 4
for t in itertools.product(li,repeat=4):
    print(f'{t[0]}.{t[1]}.{t[2]}.{t[3]}')

.....
0.1.121.217
0.1.121.218
0.1.121.219
0.1.121.220
0.1.121.221
0.1.121.222
0.1.121.223
0.1.121.224
......
6 年前
回复了 Devesh Kumar Singh 创建的主题 » csv到python字典

代码中的一些问题和建议:

  • 你在新线分裂 \n ,位于行的末尾,因此列表中只能有一个项目。您不能从中提取两个项目,因此您可以 ValueError: not enough values to unpack (expected 2, got 1) 错误
  • 你需要分开 , 而不是 \n ,因为值由 ,
  • 你可以使用 with 打开文件的上下文管理器
  • 您需要跳过文件的第一行,使用 next()
  • 你可以使用 extended iterable unpacking 输出名称和值,然后创建字典

将所有这些放在一起,重构的代码可能看起来像

race_dict = {}

#Use with to open the file
with open('file.txt', 'r') as race_read:

    #Skip the first line
    next(race_read)

    #Read all lines in a list
    race_open = race_read.readlines()

    #Iterate through the list
    for line in race_open:
        #Extract names and float values by splitting on ,
        key, *val = line.strip().split(',')

        #Convert all strings in val to float
        race_dict[key] = list(map(float, val))

print(race_dict)

所以如果输入文件是

Class mate, distance1, distance2, distance3, distance4
Bob, 102.5, 0.5587, 45.77, 49.225
Sally, 785.115, 32145.01, 4578.25, 0.5587
Anne, 4521.87, 12.5, 0.2547, 1545.554

输出将是

{'Bob': [102.5, 0.5587, 45.77, 49.225], 
'Sally': [785.115, 32145.01, 4578.25, 0.5587], 
'Anne': [4521.87, 12.5, 0.2547, 1545.554]}