关于将input().split()与3+项一起使用

  • 本文关键字:一起 split input python
  • 更新时间 :
  • 英文 :


我目前正在开发一个处理用户输入的程序,我遇到了一个input()下需要多个返回的情况,起初我不知道我在做什么当我遇到值错误,直到我查找如何做到这一点,它向我展示了并且使用 2 个输入和 input().split()

class userinput():
def __init__(self, name,lista,listb,listc,listd):
    self.name=""
    self.lista=lista
    self.listb=listb
    self.listc=listc
    self.listd=listd



def set_lists(self):
    print("Do you want to create lists")
    decision = input()       
    if decision == "yes":   
        print("how many lists would you like to create?(up to 4)")
        decision2= int(input())
        if decision2 == 1:
            print("what would you like the list to be named")
            self.lista=input()
            print("you have created 1 list, with the name:"+ self.lista)                                         
        elif decision2 == 2:
            print("what would you like your lists to be?")
            self.lista,self.listb=input().split(",")
            print("You have created 2 lists with the names," + self.lista ,self.listb)
        elif decision2 == 3:
            print("what name would you like your first 2 lists to be")
            self.lista,self.listb = input().split(",")
            print("finally, the name for your third")
            self.listc = input()
            print("you have created 3 lists with the names," +self.lista,self.listb,self.listc)
        elif decision2 == 4:
            print("what name would you like your first 2 lists to be")
            self.lista,self.listb = input().split(",")
            print("finally, for your last 2 lists") 
            self.listc,self.listd=input().split(",")
            print("you have created three lists with the names of," +self.lista,self.listb,self.listc,self.listd)
        else:
            print("quitting")
            return
    else:
        print("quitting")

我的问题:似乎没有必要将 2 个input().split()用于 4 个输入,有没有办法清理它?

你有几个问题,这里有很多重复。一种具有一些改进的方法:

decision = input("Do you want to create lists?")
if decision.lower() in ("y", "yes"):
    list_count = int(input("How many lists?"))
    names = input("Enter list names (separated by commas):").split(",")
    if len(names) != list_count:
        raise ValueError("Expected {0} names, got {1}".format(list_count, 
                                                              len(names)))
    self.lists = {name: [] for name in names} # dictionary of empty lists
    print("Created {0} lists.".format(list_count))

(注意 Python 2.x 使用 raw_input )。

split创建一个列表,其中包含字符串可以拆分为的尽可能多的项目,除非受到第二个可选参数maxsplit约束:

"a,b,c".split(",") == ["a", "b", "c"]
"a,b,c".split(",", 1) == ["a", "b,c"]
我认为

这段代码会更干净一些。

    print("Do you want to create lists")
    decision = input()       
    if decision == "yes":   
        print("how many lists would you like to create?(up to 4)")
        decision2= int(input())
        print("What would you like the lists named?")
        listnames = input()
        lists = listnames.split()
        print("you have created %i lists with the following names: %s"%(decision2, ",".join(lists)))
    else:
        print("quitting")
a, b, c, d = raw_input("what name would you like your 4 lists to ben").split(',')

split可以将字符串分成两部分以上。

我只会这样做:

def set_lists(self):
    print("Do you want to create lists")
    decision = input()       
    if decision.lower().startswith("y"):   
        print("how many lists would you like to create? (up to 4)")
        decision2 = int(input())
        if decision2 == 1:
                print("what would you like the list to be named")
                self.lists = [input()]
                print("you have created 1 list, with the name:"+ self.lists[0])                                         
        elif 2 <= decision2 <= 4:
            print("Enter your lists' names, seperated by commas")
            self.lists = input().split(",")
            if len(self.lists) != decision2:
                print("You didn't enter the right amount of names!")
            else:
                print("You have created {} lists with the names {}".format(decision2, ", ".join(map(str, self.lists)))
        else:
            print("quitting")
    else:
        print("quitting")

然后做self.lists[0]self.lists[1]等而不是self.listaself.listb

最新更新