如何使用逗号在Python中合并列表中的2个元素?

问题描述:

让我们假设我有一个表,如下所示:如何使用逗号在Python中合并列表中的2个元素?

['a', '256','c','d'] 

我的输出应该

['a','256,c','d'] 

我会更喜欢它修改现有列表直接,而不是创建一个新的列表。

+0

肯定的:L = [ 'A', 'B', 'C'] 为指数,产品在枚举(L): \t L [0] = L [0] + L [1] + L [2] \t print L –

+0

编辑您的问题并将该代码放在那里,并确保它使用格式化工具进行格式化。此外,解释为什么你的代码不按照你认为应该的方式工作。 – idjaw

+0

你在找什么算法?你做了什么尝试?实际上,这可以通过'mylist [:] = ['a','256,c','d']'来回答。 – TigerhawkT3

尝试此

列表= [ '一个', '256', 'C', 'd']

列表[1] = “”。加入(项目为项目在名单[1:3]) 希望这是你想要什么

如果你想合并的第二和第三元素试试这个

lst = ['a', '256', 'c', 'd'] 

lst[1] += ',' + lst[2] 
del(lst[2]) 

基本上我想提取泰坦尼克号数据集合W没有使用熊猫这是我们大学给出的任务。泰坦尼克号数据集链接如下: https://vincentarelbundock.github.io/Rdatasets/datasets.html

我已经写这将在下面给出的完整的解决方案:

# isReal function will check whether the given string txt is a floating point number or not. and returns true if it is, and false otherwise. 
def isReal(txt): 
    try: 
     float(txt) 
     return True 
    except ValueError: 
     return False 
# myload is a function that will load the dataset with the given file_name and strips all the unwanted characters like '"','\r','\n',and splits with ',' being the delimiter and this is done with the help of split function then it puts each word in a line in the data set into a list and this list is appended into another list (basically creating list of lists) before this we insert ',' as an element in the list and then use the join function to merge the names of the passengers as a single element in the list and then finally we convert each of the integer element which are string type into integer and same way floats and replace them in the list which finishes the job. Finally we pop the first list from the list of lists. 
def myload(file_name): 
    L=[] 
    with open('train.csv') as f: 
     for line in f: 
      line=line.rstrip('\r\n') 
      l=[element.strip('"') for element in line.split(',')] 
      l.insert(4,',') 
      L.append(l) 

    for l in L: 
     l[3:6]=[''.join(l[3:6])] 
    for l in L: 
     for index, elem in enumerate(l): 
      if l[index].isdigit() == True: 
       l[index]=int(l[index]) 
      else: 
       if isReal(l[index]) == True: 
        l[index]=float(l[index]) 
    L.pop(0)     
    return L 
Li=[] 
nb=input('enter the number of lines u want to display:') 
nb=int(nb) 
i=0 
Li = myload('train.csv') 
while i < nb: 
    print(Li[i]) 
    i+=1